Given a binary tree and a number, the task is to return the length of the shortest path beginning at root and ending at a leaf node such that the sum of numbers along that path is equal to ‘sum’. Print “-1” if no such path exists.
Input: 1 / \ 10 15 / \ 5 2 Number = 16 Output: 2 There are two paths: 1->15, length of path is 3 1->10->5, length of path is 2 Input: 1 / \ 10 15 / \ 5 2 Number = 20 Output: -1 There exists no such path with 20 as sum from root to any node
Source: Microsoft Interview
Approach: An approach to check whether such a path exists or not has been discussed in this post. The below steps can be followed to find the shortest path.
- Recursively call the left and right child with path sum and level to ( number – value at the current node, level+1).
- If the leaf node is reached, then store the minimum of all the levels of the leaf node.
Below is the implementation of the above approach:
There is a root-to-leaf path with sum 16 and the shortest path length is: 1
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.
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print the first shortest root to leaf path in a Binary Tree
- Root to leaf path sum equal to a given number in BST
- Root to leaf path sum equal to a given number
- Root to leaf path product equal to a given number
- Find the maximum sum leaf to root path in a Binary Tree
- Sum of nodes on the longest path from root to leaf node
- Find all root to leaf path sum of a Binary Tree
- Check if there is a root to leaf path with given sequence
- Print the longest leaf to leaf path in a Binary tree
- GCD from root to leaf path in an N-ary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Root to leaf path with maximum distinct nodes
- Print the longest path from root to leaf in a Binary tree
- Root to leaf paths having equal lengths in a Binary Tree
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Sum of all the numbers that are formed from root to leaf paths
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Given a binary tree, print out all of its root-to-leaf paths one per line.
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.