Algorithm to print all paths with a given sum in a binary tree

后端 未结 18 1388
既然无缘
既然无缘 2020-12-24 07:04

The following is an interview question.

You are given a binary tree (not necessarily BST) in which each node contains a value. Design an algorithm t

18条回答
  •  悲&欢浪女
    2020-12-24 07:27

    // assumption node have integer value other than zero
    void printAllPaths(Node root, int sum , ArrayList path) {
    
       if(sum == 0) {
          print(path); // simply print the arraylist
        }
    
       if(root ==null) {
         //traversed one end of the tree...just return
          return;
      }
        int data = root.data;
        //this node can be at the start, end or in middle of path only if it is       //less than the sum
        if(data<=sum) {
         list.add(data);
         //go left and right
        printAllPaths(root.left, sum-data ,  path);
        printAllPaths(root.right, sum-data ,  path);
    
        }
       //note it is not else condition to ensure root can start from anywhere
       printAllPaths(root.left, sum ,  path);
       printAllPaths(root.right, sum ,  path);
    }
    

提交回复
热议问题