This post is completed by 2 users

  • 0
Add to List
Medium

135. Find Paths with Sum in Binary Tree

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

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

Approach:

  1. Do the preorder traversal.
  2. take a variable path and pass it in each recursive call.
  3. if the root is greater than the Sum required, and return.
  4. If not then, add root to the path and update the required sum (sum=sum-root.data).
  5. if the sum required =0, means we have found the route, print the path.
  6. See the code for a better understanding.
 
1 2 7
1 3 6