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.
Input : Input : sum = 8, Root of tree 1 / \ 20 3 / \ 4 15 / \ / \ 6 7 8 9 Output : Path: 1 3 4 Input : sum = 38, Root of tree 10 / \ 28 13 / \ 14 15 / \ / \ 21 22 23 24 Output : Path found: 10 28 Path found: 10 13 15
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.
Path found: 10 28 Path found: 10 13 15
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 email@example.com. 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.
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Root to leaf paths having equal lengths in a Binary Tree
- Print all k-sum paths in a binary tree
- Print path from root to a given node in a binary tree
- Print path from root to all nodes in a Complete Binary Tree
- Print the first shortest root to leaf path in a Binary Tree
- Print root to leaf paths without using recursion
- Print all root to leaf paths with there relative positions
- Print the path common to the two paths from the root to the two given nodes
- Count all k-sum paths in a Binary Tree
- Sort the path from root to a given node in a Binary Tree
- Find distance from root to given node in a binary tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
Improved By : SHUBHAMSINGH10