This post is completed by 1 user

  • 0
Add to List
Medium

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 the path equals a given number.
Example:

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

Approach:

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

Code:


1 2 7
1 3 6



Also Read: