Given a binary tree and a sum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Return false if no such path can be found. Example:
Input:
Output: True Explanation: Root to leaf path sum, existing in this tree are:
[Expected Approach - 1] Using Recursion - O(n) Time and O(h) Space
The idea is to recursively move to left and right subtree and decrease sum by the value of the current node and if at any point the current node is equal to a leaf node and remaining sum is equal to zero then the answer is true.
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.
Below is the implementation of the above approach:
C++
// C++ Program to Check if Root to leaf path// sum equal to a given number#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intkey){data=key;left=nullptr;right=nullptr;}};// Given a tree and a sum, return true if there is a path from// the root down to a leaf, such that adding up all the values// along the path equals the given sum.boolhasPathSum(Node*root,intsum){if(root==NULL)return0;intsubSum=sum-root->data;// If we reach a leaf node and sum becomes 0 then return trueif(subSum==0&&root->left==nullptr&&root->right==nullptr)return1;// Otherwise check both subtreesboolleft=0,right=0;if(root->left)left=hasPathSum(root->left,subSum);if(root->right)right=hasPathSum(root->right,subSum);returnleft||right;}intmain(){intsum=21;// Constructed binary tree is// 10// / \ // 8 2// / \ /// 3 5 2Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->left->right=newNode(5);root->right->left=newNode(2);if(hasPathSum(root,sum)){cout<<"True"<<endl;}elsecout<<"False";return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to check if there is a root-to-leaf // path with a given suminthasPathSum(structNode*root,intsum){if(root==NULL){returnsum==0;}intsubSum=sum-root->data;// If we reach a leaf node and sum becomes// 0 then return trueif(subSum==0&&root->left==NULL&&root->right==NULL){return1;}// Otherwise check both subtreesreturnhasPathSum(root->left,subSum)||hasPathSum(root->right,subSum);}structNode*createNode(intkey){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=key;node->left=NULL;node->right=NULL;returnnode;}intmain(){// Constructed binary tree is// 10// / \ // 8 2// / \ /// 3 5 2intsum=21;structNode*root=createNode(10);root->left=createNode(8);root->right=createNode(2);root->left->left=createNode(3);root->left->right=createNode(5);root->right->left=createNode(2);if(hasPathSum(root,sum)){printf("True\n");}else{printf("False\n");}return0;}
Java
// Java Program to Check if Root to leaf path // sum equal to a given numberclassNode{Nodeleft,right;intdata;Node(intkey){data=key;left=null;right=null;}}classGfG{// Given a tree and a sum, return true if there is a path from// the root down to a leaf, such that adding up all the values// along the path equals the given sum.staticbooleanhasPathSum(Noderoot,intsum){if(root==null)returnfalse;intsubSum=sum-root.data;// If we reach a leaf node and sum becomes 0 then return trueif(subSum==0&&root.left==null&&root.right==null)returntrue;// Otherwise check both subtreesbooleanleft=false,right=false;if(root.left!=null)left=hasPathSum(root.left,subSum);if(root.right!=null)right=hasPathSum(root.right,subSum);returnleft||right;}publicstaticvoidmain(String[]args){intsum=21;// Constructed binary tree is// 10// / \// 8 2// / \ /// 3 5 2Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);System.out.println(hasPathSum(root,sum));}}
Python
# Python Program to Check if Root to leaf path# sum equal to a given numberclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Given a tree and a sum, return true if there is a path from# the root down to a leaf, such that adding up all the values# along the path equals the given sum.defhasPathSum(root,sum):ifrootisNone:returnFalsesubSum=sum-root.data# If we reach a leaf node and sum becomes 0 then return trueifsubSum==0androot.leftisNoneandroot.rightisNone:returnTrue# Otherwise check both subtreesleft=hasPathSum(root.left,subSum)ifroot.leftelseFalseright=hasPathSum(root.right,subSum)ifroot.rightelseFalsereturnleftorrightif__name__=="__main__":sum=21# Constructed binary tree is# 10# / \# 8 2# / \ /# 3 5 2root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.left.right=Node(5)root.right.left=Node(2)print(hasPathSum(root,sum))
C#
// C# Program to Check if Root to leaf path// sum equal to a given number usingSystem;classNode{publicNodeleft,right;publicintdata;publicNode(intkey){data=key;left=null;right=null;}}classGfG{// Given a tree and a sum, return true if there is a path from// the root down to a leaf, such that adding up all the values// along the path equals the given sum.staticboolHasPathSum(Noderoot,intsum){if(root==null)returnfalse;intsubSum=sum-root.data;// If we reach a leaf node and sum becomes 0 then return trueif(subSum==0&&root.left==null&&root.right==null)returntrue;// Otherwise check both subtreesboolleft=false,right=false;if(root.left!=null)left=HasPathSum(root.left,subSum);if(root.right!=null)right=HasPathSum(root.right,subSum);returnleft||right;}staticvoidMain(string[]args){intsum=21;// Constructed binary tree is// 10// / \// 8 2// / \ /// 3 5 2Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);Console.WriteLine(HasPathSum(root,sum));}}
JavaScript
// JavaScript Program to Check if Root to leaf// path sum equal to a given numberclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Given a tree and a sum, return true if there is a path from// the root down to a leaf, such that adding up all the values// along the path equals the given sum.functionhasPathSum(root,sum){if(root===null)returnfalse;constsubSum=sum-root.data;// If we reach a leaf node and sum becomes 0 then return trueif(subSum===0&&root.left===null&&root.right===null)returntrue;// Otherwise check both subtreesconstleft=root.left?hasPathSum(root.left,subSum):false;constright=root.right?hasPathSum(root.right,subSum):false;returnleft||right;}// Constructed binary tree is// 10// / \// 8 2// / \ /// 3 5 2constsum=21;constroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);console.log(hasPathSum(root,sum));
Output
True
Time Complexity: O(n), where n is the number of nodes. Auxiliary Space: O(h), where h is the height of the tree.
[Expected Approach - 2] Using Iterative - O(n) Time and O(h) Space
In this approach, we use a stack to perform a preorder traversal of the binary tree. We maintain two stacks - one to store the nodes and another to store the sum of values along the path to that node. Whenever we encounter a leaf node, we check if the sum matches the target sum. If it does, we return true, otherwise, we continue traversing the tree.
Follow the given steps to solve the problem using the above approach:
Check if the root node is NULL. If it is, return false, since there is no path to follow.
Create two stacks, one for the nodes and one for the sums. Push the root node onto the node stack and its data onto the sum stack. While the node stack is not empty, do the following:
Pop a node from the node stack and its corresponding sum from the sum stack.
Check if the node is a leaf node (i.e., it has no left or right child). If it is, check if the sum equals the target sum. If it does, return true, since we have found a path that adds up to the target sum.
If the node has a left child, push it onto the node stack and push the sum plus the left child’s data onto the sum stack.
If the node has a right child, push it onto the node stack and push the sum plus the right child’s data onto the sum stack.
If we reach this point, it means we have exhausted all paths and haven’t found any that add up to the target sum. Return false.
Below is the implementation of the above approach:
C++
// C++ Program to Check if Root to leaf path sum // equal to a given number#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intkey){data=key;left=nullptr;right=nullptr;}};// Check if there's a root-to-leaf path with the given sumboolhasPathSum(Node*root,inttargetSum){if(root==nullptr)returnfalse;stack<Node*>stk;stack<int>sums;stk.push(root);sums.push(root->data);while(!stk.empty()){Node*node=stk.top();stk.pop();intsum=sums.top();sums.pop();// Check if leaf node and sum matchesif(node->left==nullptr&&node->right==nullptr&&sum==targetSum)returntrue;// Add children to stacks with updated sumsif(node->left){stk.push(node->left);sums.push(sum+node->left->data);}if(node->right){stk.push(node->right);sums.push(sum+node->right->data);}}returnfalse;}intmain(){// Construct binary tree// 10// / \ // 8 2// / \ /// 3 5 2Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->left->right=newNode(5);root->right->left=newNode(2);inttargetSum=21;if(hasPathSum(root,targetSum)){cout<<"True"<<endl;}elsecout<<"False";return0;}
Java
// Java Program to Check if Root to leaf path // sum equal to a given number importjava.util.Stack;classNode{Nodeleft,right;intdata;Node(intkey){data=key;left=null;right=null;}}classGfG{// Check if there's a root-to-leaf path with the given sumstaticbooleanhasPathSum(Noderoot,inttargetSum){if(root==null)returnfalse;Stack<Node>stk=newStack<>();Stack<Integer>sums=newStack<>();stk.push(root);sums.push(root.data);while(!stk.isEmpty()){Nodenode=stk.pop();intsum=sums.pop();// Check if leaf node and sum matchesif(node.left==null&&node.right==null&&sum==targetSum)returntrue;// Add children to stacks with updated sumsif(node.left!=null){stk.push(node.left);sums.push(sum+node.left.data);}if(node.right!=null){stk.push(node.right);sums.push(sum+node.right.data);}}returnfalse;}publicstaticvoidmain(String[]args){// Construct binary tree// 10// / \// 8 2// / \ /// 3 5 2Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);inttargetSum=21;System.out.println(hasPathSum(root,targetSum));}}
Python
# Python Program to Check if Root to leaf path # sum equal to a given number classNode:def__init__(self,key):self.data=keyself.left=Noneself.right=None# Check if there's a root-to-leaf path with# the given sumdefhasPathSum(root,targetSum):ifrootisNone:returnFalsestack=[]sums=[]stack.append(root)sums.append(root.data)whilestack:node=stack.pop()sumValue=sums.pop()# Check if leaf node and sum matchesifnode.leftisNoneandnode.rightisNone \
andsumValue==targetSum:returnTrue# Add children to stacks with updated sumsifnode.left:stack.append(node.left)sums.append(sumValue+node.left.data)ifnode.right:stack.append(node.right)sums.append(sumValue+node.right.data)returnFalseif__name__=="__main__":# Construct binary tree# 10# / \# 8 2# / \ /# 3 5 2root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.left.right=Node(5)root.right.left=Node(2)targetSum=21print(hasPathSum(root,targetSum))
C#
// C# Program to Check if Root to leaf path// sum equal to a given number usingSystem;usingSystem.Collections.Generic;classNode{publicNodeleft,right;publicintdata;publicNode(intkey){data=key;left=null;right=null;}}classGfG{// Check if there's a root-to-leaf path with the given sumstaticboolhasPathSum(Noderoot,inttargetSum){if(root==null)returnfalse;Stack<Node>stk=newStack<Node>();Stack<int>sums=newStack<int>();stk.Push(root);sums.Push(root.data);while(stk.Count>0){Nodenode=stk.Pop();intsum=sums.Pop();// Check if leaf node and sum matchesif(node.left==null&&node.right==null&&sum==targetSum)returntrue;// Add children to stacks with updated sumsif(node.left!=null){stk.Push(node.left);sums.Push(sum+node.left.data);}if(node.right!=null){stk.Push(node.right);sums.Push(sum+node.right.data);}}returnfalse;}staticvoidMain(string[]args){// Construct binary tree// 10// / \// 8 2// / \ /// 3 5 2Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);inttargetSum=21;Console.WriteLine(hasPathSum(root,targetSum));}}
JavaScript
// JavaScript Program to Check if Root to leaf// path sum equal to a given number classNode{constructor(key){this.data=key;this.left=null;this.right=null;}}// Check if there's a root-to-leaf path // with the given sumfunctionhasPathSum(root,targetSum){if(root===null)returnfalse;conststack=[];constsums=[];stack.push(root);sums.push(root.data);while(stack.length>0){constnode=stack.pop();constsum=sums.pop();// Check if leaf node and sum matchesif(node.left===null&&node.right===null&&sum===targetSum)returntrue;// Add children to stacks with updated sumsif(node.left){stack.push(node.left);sums.push(sum+node.left.data);}if(node.right){stack.push(node.right);sums.push(sum+node.right.data);}}returnfalse;}// Construct binary tree// 10// / \// 8 2// / \ /// 3 5 2constroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.left.right=newNode(5);root.right.left=newNode(2);consttargetSum=21;console.log(hasPathSum(root,targetSum));
Output
True
Time Complexity: O(n) where n is the number of nodes. Auxiliary Space: O(h) where h is the height of the tree.