Print All Paths From Root In a Binary Tree Whose Sum is Equal to a Given Number

Objective: – Given a binary tree and X, write an algorithm to Print all the paths starting from root so that sum of all the nodes in path equals to a given number.
Example:

Print All Paths From Root In a Binary Tree Whose Sum is Equal to a Given Number

Approach:

  • Create a global variable as String = path.
  • Do the preorder
  • if root is greater than Sum required, return.
  • If not then, add root to the path and update the required sum (sum=sum-root.data).
  • if sum required =0, means we have found the path, print it.
  • See the code for better understanding.

Code:


Output:

1 2 7
1 3 6

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: