Shortest root to leaf path sum equal to a given number

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.

Examples:

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to left child 
and a pointer to right child */
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
  
// Function to find the shortes path from root 
// to leaf with given sum
void hasPathSum(struct Node* node, int sum,
                     int& mini, int level)
{
    // check if leaf node and check sum
    if (node == NULL) {
  
        // Store the minimum path
        if (sum == 0)
            mini = min(level - 1, mini);
  
        return;
    }
    else {
        int subSum = sum - (node->data);
  
        // Recur in the left tree
        hasPathSum(node->left, subSum, mini, level + 1);
  
        // Recur in the right tree
        hasPathSum(node->right, subSum, mini, level + 1);
    }
}
  
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the 
given data and NULL left and right pointers. */
struct Node* newnode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = NULL;
    node->right = NULL;
  
    return (node);
}
  
/* Driver program to test above functions*/
int main()
{
  
    int sum = 16;
  
    /* Constructed binary tree is 
          
                 1
             /       \ 
          10         15 
       /      \     
     5        2 
*/
    struct Node* root = newnode(1);
    root->left = newnode(10);
    root->right = newnode(15);
    root->left->left = newnode(5);
    root->left->right = newnode(2);
  
    int mini = INT_MAX;
  
    // Function call
    hasPathSum(root, sum, mini, 0);
  
    if (mini != INT_MAX)
        printf("There is a root-to-leaf path with sum %d\n"
               "and the shortest path length is: %d",
               sum, mini);
    else
        printf("There is no root-to-leaf path with sum %d", sum);
  
    return 0;
}

chevron_right


Output:

There is a root-to-leaf path with sum 16
and the shortest path length is: 1


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.