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.

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


  • 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 (
  • if sum required =0, means we have found the path, print it.
  • See the code for better understanding.



1 2 7
1 3 6

Top Companies Interview Questions..-


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

You may also like...

2 Responses

  1. Eugen Daroczy says:

    By doing the preorder traversal, on the left branch all of the 1, 2, 7 and 5 nodes will be added; is that a valid scenario? Since I’m asking I guess that is not a valid path.

    The solution also does not catch the scenario where sum = 12. In that context, the path would consist only of nodes 2, 1, 3 and 6. I’d guess that is a valid path in the tree, right?

    • tutorialhorizon says:

      Thanks Eugen. It was a solution for some other problem. I have updated the post. Do let me know if you find issues in other posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: