Given a Binary tree and a sum S, print all the paths, starting from root, that sums upto the given sum. Note that this problem is different from root to leaf paths. Here path doesn’t need to end on a leaf node.
For this problem, preorder traversal is best suited as we have to add up a key value as we land on that node. We start from the root and start traversing by preorder traversal, adding key value to the sum_so_far and checking whether it is equal to the required sum. Also, as tree node doesn’t have a pointer pointing to its parent, we have to explicitly save from where we have moved. We use a vector path to store the path for this. Every node in this path contributes to the sum_so_far.
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.