Given root of a binary tree and an integer target, 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. Examples:
Input: root = [1, 2, 3, 4, 1], target = 4
Output: true Explanation: The root to leaf path sums are 1 + 2 + 4 = 7, 1 + 2 + 1 = 4 and 1 + 3 = 4. Since, a path with sum 4 exists (1 -> 3 and 1 -> 2 -> 1), the answer is true.
Input: root = [1, 2, 3], target = 2
Output: false Explanation: The root to leaf path sums are 1 + 2 = 3 and 1 + 3 = 4. Since, there is no path with sum 2, the answer is false.
The idea is to recursively move to left and right subtree and decrease sum by the value of the current node. If at any point the current node is a leaf node and remaining sum is equal to zero then the answer is true.
If the tree is empty, return false.
Subtract the current node's value from target.
If the current node is a leaf, return true if the remaining target is 0; otherwise return false.
Recursively check the left and right subtrees with the updated target.
Return true if either subtree contains a valid root-to-leaf path; otherwise return false.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intkey){data=key;left=right=nullptr;}};boolhasPathSum(Node*root,inttarget){// Empty tree has no valid path.if(root==nullptr)returnfalse;// Subtract current node's value from the remaining sum.target-=root->data;// If this is a leaf and the remaining sum is 0,// a valid root-to-leaf path is found.if(root->left==nullptr&&root->right==nullptr)returntarget==0;// Check both subtrees.returnhasPathSum(root->left,target)||hasPathSum(root->right,target);}intmain(){inttarget=21;// Construct the 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);cout<<(hasPathSum(root,target)?"true":"false");return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};structNode*newNode(intkey){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=key;node->left=node->right=NULL;returnnode;}inthasPathSum(structNode*root,inttarget){// Empty tree has no valid path.if(root==NULL)return0;// Subtract current node's value from the remaining sum.target-=root->data;// If this is a leaf and the remaining sum is 0,// a valid root-to-leaf path is found.if(root->left==NULL&&root->right==NULL)returntarget==0;// Check both subtrees.returnhasPathSum(root->left,target)||hasPathSum(root->right,target);}intmain(){inttarget=21;// Construct the binary tree://// 10// / \ // 8 2// / \ /// 3 5 2structNode*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);printf("%s",hasPathSum(root,target)?"true":"false");return0;}
Java
classNode{intdata;Nodeleft,right;Node(intkey){data=key;left=right=null;}}classGFG{staticbooleanhasPathSum(Noderoot,inttarget){// Empty tree has no valid path.if(root==null)returnfalse;// Subtract current node's value from the remaining// sum.target-=root.data;// If this is a leaf and the remaining sum is 0,// a valid root-to-leaf path is found.if(root.left==null&&root.right==null)returntarget==0;// Check both subtrees.returnhasPathSum(root.left,target)||hasPathSum(root.right,target);}publicstaticvoidmain(String[]args){inttarget=21;// Construct the 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);System.out.print(hasPathSum(root,target)?"true":"false");}}
Python
classNode:def__init__(self,key):self.data=keyself.left=Noneself.right=NonedefhasPathSum(root,target):# Empty tree has no valid path.ifrootisNone:returnFalse# Subtract current node's value from the remaining sum.target-=root.data# If this is a leaf and the remaining sum is 0,# a valid root-to-leaf path is found.ifroot.leftisNoneandroot.rightisNone:returntarget==0# Check both subtrees.returnhasPathSum(root.left,target)orhasPathSum(root.right,target)# Driver Codeif__name__=="__main__":target=21# Construct the 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)print("true"ifhasPathSum(root,target)else"false")
C#
usingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intkey){data=key;left=right=null;}}classGFG{staticboolhasPathSum(Noderoot,inttarget){// Empty tree has no valid path.if(root==null)returnfalse;// Subtract current node's value from the remaining// sum.target-=root.data;// If this is a leaf and the remaining sum is 0,// a valid root-to-leaf path is found.if(root.left==null&&root.right==null)returntarget==0;// Check both subtrees.returnhasPathSum(root.left,target)||hasPathSum(root.right,target);}staticvoidMain(){inttarget=21;// Construct the 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);Console.Write(hasPathSum(root,target)?"true":"false");}}
JavaScript
classNode{constructor(key){this.key=key;this.left=null;this.right=null;}}functionhasPathSum(root,target){// Empty tree has no valid path.if(root===null)returnfalse;// Subtract current node's value from the remaining sum.target-=root.key;// If this is a leaf and the remaining sum is 0,// a valid root-to-leaf path is found.if(root.left===null&&root.right===null)returntarget===0;// Check both subtrees.returnhasPathSum(root.left,target)||hasPathSum(root.right,target);}// Driver Codeconsttarget=21;// Construct the 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);console.log(hasPathSum(root,target)?"true":"false");
Output
true
Iterative - O(n) Time and O(h) Space
We use stack based iterative preorder traversal. 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:
Step 1 : 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.
Step 2: 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 If it is, check if the sum equals the target sum. If it does, return true.
If the node has a leftchild, push it onto the node stackand 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.
Step 3: If we reach this point, it means we have exhaustedall paths and haven’t found any that add up to the target sum.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intkey){data=key;left=right=nullptr;}};boolhasPathSum(Node*root,inttarget){// Empty tree has no valid path.if(root==nullptr)returnfalse;// Stack for nodes and their corresponding path sums.stack<Node*>nodeStack;stack<int>sumStack;nodeStack.push(root);sumStack.push(root->data);while(!nodeStack.empty()){// Get the current node and its path sum.Node*current=nodeStack.top();nodeStack.pop();intcurrentSum=sumStack.top();sumStack.pop();// If current node is a leaf and its path sum// matches the target, a valid path is found.if(current->left==nullptr&¤t->right==nullptr&¤tSum==target){returntrue;}// Add the left child with its updated path sum.if(current->left!=nullptr){nodeStack.push(current->left);sumStack.push(currentSum+current->left->data);}// Add the right child with its updated path sum.if(current->right!=nullptr){nodeStack.push(current->right);sumStack.push(currentSum+current->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);inttarget=21;cout<<(hasPathSum(root,target)?"true":"false");return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intkey){data=key;left=right=null;}}classGFG{staticbooleanhasPathSum(Noderoot,inttarget){// Empty tree has no valid path.if(root==null)returnfalse;// Stack for nodes and their corresponding path// sums.Stack<Node>nodeStack=newStack<>();Stack<Integer>sumStack=newStack<>();nodeStack.push(root);sumStack.push(root.data);while(!nodeStack.empty()){// Get the current node and its path sum.Nodecurrent=nodeStack.pop();intcurrentSum=sumStack.pop();// If current node is a leaf and its path sum// matches the target, a valid path is found.if(current.left==null&¤t.right==null&¤tSum==target){returntrue;}// Add the left child with its updated path sum.if(current.left!=null){nodeStack.push(current.left);sumStack.push(currentSum+current.left.data);}// Add the right child with its updated path// sum.if(current.right!=null){nodeStack.push(current.right);sumStack.push(currentSum+current.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);inttarget=21;System.out.print(hasPathSum(root,target)?"true":"false");}}
Python
classNode:def__init__(self,key):self.data=keyself.left=Noneself.right=NonedefhasPathSum(root,target):# Empty tree has no valid path.ifrootisNone:returnFalse# Stack for nodes and their corresponding path sums.nodeStack=[]sumStack=[]nodeStack.append(root)sumStack.append(root.data)whilenodeStack:# Get the current node and its path sum.current=nodeStack.pop()currentSum=sumStack.pop()# If current node is a leaf and its path sum# matches the target, a valid path is found.if(current.leftisNoneandcurrent.rightisNoneandcurrentSum==target):returnTrue# Add the left child with its updated path sum.ifcurrent.leftisnotNone:nodeStack.append(current.left)sumStack.append(currentSum+current.left.data)# Add the right child with its updated path sum.ifcurrent.rightisnotNone:nodeStack.append(current.right)sumStack.append(currentSum+current.right.data)returnFalse# Driver Codeif__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)target=21print("true"ifhasPathSum(root,target)else"false")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intkey){data=key;left=right=null;}}classGFG{staticboolhasPathSum(Noderoot,inttarget){// Empty tree has no valid path.if(root==null)returnfalse;// Stack for nodes and their corresponding path// sums.Stack<Node>nodeStack=newStack<Node>();Stack<int>sumStack=newStack<int>();nodeStack.Push(root);sumStack.Push(root.data);while(nodeStack.Count>0){// Get the current node and its path sum.Nodecurrent=nodeStack.Pop();intcurrentSum=sumStack.Pop();// If current node is a leaf and its path sum// matches the target, a valid path is found.if(current.left==null&¤t.right==null&¤tSum==target){returntrue;}// Add the left child with its updated path sum.if(current.left!=null){nodeStack.Push(current.left);sumStack.Push(currentSum+current.left.data);}// Add the right child with its updated path// sum.if(current.right!=null){nodeStack.Push(current.right);sumStack.Push(currentSum+current.right.data);}}returnfalse;}staticvoidMain(){// 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);inttarget=21;Console.Write(hasPathSum(root,target)?"true":"false");}}
JavaScript
classNode{constructor(key){this.key=key;this.left=null;this.right=null;}}functionhasPathSum(root,target){// Empty tree has no valid path.if(root===null)returnfalse;// Stack for nodes and their corresponding path sums.constnodeStack=[];constsumStack=[];nodeStack.push(root);sumStack.push(root.key);while(nodeStack.length>0){// Get the current node and its path sum.constcurrent=nodeStack.pop();constcurrentSum=sumStack.pop();// If current node is a leaf and its path sum// matches the target, a valid path is found.if(current.left===null&¤t.right===null&¤tSum===target){returntrue;}// Add the left child with its updated path sum.if(current.left!==null){nodeStack.push(current.left);sumStack.push(currentSum+current.left.key);}// Add the right child with its updated path sum.if(current.right!==null){nodeStack.push(current.right);sumStack.push(currentSum+current.right.key);}}returnfalse;}// Driver Code// 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);consttarget=21;console.log(hasPathSum(root,target)?"true":"false");