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
- Root to leaf path sum equal to a given number
- Root to leaf path sum equal to a given number in BST
- Root to leaf path product equal to a given number
- Print the first shortest root to leaf path in a Binary Tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- GCD from root to leaf path in an N-ary tree
- Check if there is a root to leaf path with given sequence
- Root to leaf path with maximum distinct nodes
- Sum of nodes on the longest path from root to leaf node
- Boundary Root to Leaf Path traversal of a Binary Tree
- Find the maximum sum leaf to root path 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
- Print the longest leaf to leaf path in a Binary tree
- Implementing a BST where every node stores the maximum number of nodes in the path till any leaf