Home » Data Structure & Algorithms » Root to leaf path sum equal to a given number in a BinaryTree

Root to leaf path sum equal to a given number in a BinaryTree

Question :
WAP to program to check if there exists a root to leaf path in the binary tree with sum of node values equal to a given number.

FYI : A leaf node is a node which has no left and right child.

Solution :
The problem is solved in recursive way.If the sum is 11 then root to leaf path 1->3->7 has sum 11.
If sum is 7,then there exists no path.

Algorithm :
Step 1 : If node is NULL then return false.
Step 2 :  Recursively check if left or right child has path sum equal to ( number – value at current node),then return result;

Program :

 


Leave a comment

Your email address will not be published. Required fields are marked *

18 − 8 =