January 10, 2025 |8.4K Views

Root to leaf path sum equal to a given number

  Share   Like
Description
Discussion

Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found. 

Example:

Input:      10          Sum = 23
             /     \
          8        2
       /    \     /
     3      5  2

Output: True 
Explanation:  Root to leaf path sum, existing in this tree are
21 –> 10 – 8 – 3 
23 –> 10 – 8 – 5 
14 –> 10 – 2 – 2
So it is possible to get sum = 23

Follow the given steps to solve the problem using the above approach:

  • Recursively move to the left and right subtree and at each call decrease the sum by the value of the current node

  • If at any level the current node is a leaf node and the remaining sum is equal to zero then return true

Related Articles : https://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/