Print all the paths from root to leaf, with a specified sum in Binary tree
Given a Binary tree, and target sum as K, the task is to print all the possible paths from root to leaf that has the sum equal to K.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: K = 22 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 Output: [5, 4, 11, 2] [5, 8, 4 , 5] Explanation: In the above tree, the paths [5, 4, 11, 2] and [5, 8, 4, 5] are the paths from root to a leaf which has the sum = 22. Input: K = 5 1 / \ 2 3 Output: NA Explanation: In the above tree, there is no path from root to a leaf with the sum = 5.
- Push the current node value into the stack .
- If the current node is a leaf node. Check if the data at the leaf node is equal to remaining target_sum.
a. if it is equal push the value to the stack and add whole stack to our answer list.
b. otherwise we don’t need this root to leaf path.
- Recursively call left subtree and right subtree by substracting the current node value from the target_sum.
- Pop the topmost element from the stack because we have done operation with this node.
Below is the implementation of the above approach:
[5, 4, 11, 2] [5, 8, 4, 5]
Time complexity: O(N)
Auxiliary space: O(N).