Root to leaf path sum equal to a given number
Last Updated :
04 Oct, 2024
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:
- 10 -> 8 -> 3 = 21
- 10 -> 8 -> 5 = 23
- 10 -> 2 -> 2 = 14
So it is possible to get sum = 21
[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>
using namespace std;
class Node {
public:
Node *left, *right;
int data;
Node(int key) {
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.
bool hasPathSum(Node* root, int sum) {
if (root == NULL)
return 0;
int subSum = sum - root->data;
// If we reach a leaf node and sum becomes 0 then return true
if (subSum == 0 && root->left == nullptr && root->right == nullptr)
return 1;
// Otherwise check both subtrees
bool left = 0, right = 0;
if (root->left)
left = hasPathSum(root->left, subSum);
if (root->right)
right = hasPathSum(root->right, subSum);
return left || right;
}
int main() {
int sum = 21;
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node* root = new Node(10);
root->left = new Node(8);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(5);
root->right->left = new Node(2);
if(hasPathSum(root, sum)) {
cout << "True"<< endl;
}
else cout << "False";
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to check if there is a root-to-leaf
// path with a given sum
int hasPathSum(struct Node* root, int sum) {
if (root == NULL) {
return sum == 0;
}
int subSum = sum - root->data;
// If we reach a leaf node and sum becomes
// 0 then return true
if (subSum == 0 && root->left == NULL
&& root->right == NULL) {
return 1;
}
// Otherwise check both subtrees
return hasPathSum(root->left, subSum)
|| hasPathSum(root->right, subSum);
}
struct Node* createNode(int key) {
struct Node* node = (
struct Node*)malloc(sizeof(struct Node));
node->data = key;
node->left = NULL;
node->right = NULL;
return node;
}
int main() {
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
int sum = 21;
struct Node* 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");
}
return 0;
}
Java
// Java Program to Check if Root to leaf path
// sum equal to a given number
class Node {
Node left, right;
int data;
Node(int key) {
data = key;
left = null;
right = null;
}
}
class GfG {
// 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.
static boolean hasPathSum(Node root, int sum) {
if (root == null) return false;
int subSum = sum - root.data;
// If we reach a leaf node and sum becomes 0 then return true
if (subSum == 0 && root.left == null
&& root.right == null) return true;
// Otherwise check both subtrees
boolean left = false, right = false;
if (root.left != null) left = hasPathSum(root.left, subSum);
if (root.right != null) right = hasPathSum(root.right, subSum);
return left || right;
}
public static void main(String[] args) {
int sum = 21;
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
System.out.println(hasPathSum(root, sum));
}
}
Python
# Python Program to Check if Root to leaf path
# sum equal to a given number
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.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.
def hasPathSum(root, sum):
if root is None:
return False
subSum = sum - root.data
# If we reach a leaf node and sum becomes 0 then return true
if subSum == 0 and root.left is None and root.right is None:
return True
# Otherwise check both subtrees
left = hasPathSum(root.left, subSum) if root.left else False
right = hasPathSum(root.right, subSum) if root.right else False
return left or right
if __name__ == "__main__":
sum = 21
# Constructed binary tree is
# 10
# / \
# 8 2
# / \ /
# 3 5 2
root = 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
using System;
class Node {
public Node left, right;
public int data;
public Node(int key) {
data = key;
left = null;
right = null;
}
}
class GfG {
// 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.
static bool HasPathSum(Node root, int sum) {
if (root == null) return false;
int subSum = sum - root.data;
// If we reach a leaf node and sum becomes 0 then return true
if (subSum == 0 && root.left == null
&& root.right == null) return true;
// Otherwise check both subtrees
bool left = false, right = false;
if (root.left != null) left = HasPathSum(root.left, subSum);
if (root.right != null) right = HasPathSum(root.right, subSum);
return left || right;
}
static void Main(string[] args) {
int sum = 21;
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
Console.WriteLine(HasPathSum(root, sum));
}
}
JavaScript
// JavaScript Program to Check if Root to leaf
// path sum equal to a given number
class Node {
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.
function hasPathSum(root, sum) {
if (root === null) return false;
const subSum = sum - root.data;
// If we reach a leaf node and sum becomes 0 then return true
if (subSum === 0 && root.left === null
&& root.right === null) return true;
// Otherwise check both subtrees
const left = root.left ? hasPathSum(root.left, subSum) : false;
const right = root.right ? hasPathSum(root.right, subSum) : false;
return left || right;
}
// Constructed binary tree is
// 10
// / \
// 8 2
// / \ /
// 3 5 2
const sum = 21;
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
console.log(hasPathSum(root, sum));
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>
using namespace std;
class Node {
public:
Node *left, *right;
int data;
Node(int key) {
data = key;
left = nullptr;
right = nullptr;
}
};
// Check if there's a root-to-leaf path with the given sum
bool hasPathSum(Node* root, int targetSum) {
if (root == nullptr) return false;
stack<Node*> stk;
stack<int> sums;
stk.push(root);
sums.push(root->data);
while (!stk.empty()) {
Node* node = stk.top();
stk.pop();
int sum = sums.top();
sums.pop();
// Check if leaf node and sum matches
if (node->left == nullptr && node->right == nullptr
&& sum == targetSum)
return true;
// Add children to stacks with updated sums
if (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);
}
}
return false;
}
int main() {
// Construct binary tree
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node* root = new Node(10);
root->left = new Node(8);
root->right = new Node(2);
root->left->left = new Node(3);
root->left->right = new Node(5);
root->right->left = new Node(2);
int targetSum = 21;
if(hasPathSum(root, targetSum)) {
cout << "True"<< endl;
}
else cout << "False";
return 0;
}
Java
// Java Program to Check if Root to leaf path
// sum equal to a given number
import java.util.Stack;
class Node {
Node left, right;
int data;
Node(int key) {
data = key;
left = null;
right = null;
}
}
class GfG {
// Check if there's a root-to-leaf path with the given sum
static boolean hasPathSum(Node root, int targetSum) {
if (root == null) return false;
Stack<Node> stk = new Stack<>();
Stack<Integer> sums = new Stack<>();
stk.push(root);
sums.push(root.data);
while (!stk.isEmpty()) {
Node node = stk.pop();
int sum = sums.pop();
// Check if leaf node and sum matches
if (node.left == null && node.right == null
&& sum == targetSum)
return true;
// Add children to stacks with updated sums
if (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);
}
}
return false;
}
public static void main(String[] args) {
// Construct binary tree
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
int targetSum = 21;
System.out.println(hasPathSum(root, targetSum));
}
}
Python
# Python Program to Check if Root to leaf path
# sum equal to a given number
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Check if there's a root-to-leaf path with
# the given sum
def hasPathSum(root, targetSum):
if root is None:
return False
stack = []
sums = []
stack.append(root)
sums.append(root.data)
while stack:
node = stack.pop()
sumValue = sums.pop()
# Check if leaf node and sum matches
if node.left is None and node.right is None \
and sumValue == targetSum:
return True
# Add children to stacks with updated sums
if node.left:
stack.append(node.left)
sums.append(sumValue + node.left.data)
if node.right:
stack.append(node.right)
sums.append(sumValue + node.right.data)
return False
if __name__ == "__main__":
# Construct binary tree
# 10
# / \
# 8 2
# / \ /
# 3 5 2
root = 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 = 21
print(hasPathSum(root, targetSum))
C#
// C# Program to Check if Root to leaf path
// sum equal to a given number
using System;
using System.Collections.Generic;
class Node {
public Node left, right;
public int data;
public Node(int key) {
data = key;
left = null;
right = null;
}
}
class GfG {
// Check if there's a root-to-leaf path with the given sum
static bool hasPathSum(Node root, int targetSum) {
if (root == null) return false;
Stack<Node> stk = new Stack<Node>();
Stack<int> sums = new Stack<int>();
stk.Push(root);
sums.Push(root.data);
while (stk.Count > 0) {
Node node = stk.Pop();
int sum = sums.Pop();
// Check if leaf node and sum matches
if (node.left == null && node.right == null
&& sum == targetSum)
return true;
// Add children to stacks with updated sums
if (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);
}
}
return false;
}
static void Main(string[] args) {
// Construct binary tree
// 10
// / \
// 8 2
// / \ /
// 3 5 2
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
int targetSum = 21;
Console.WriteLine(hasPathSum(root, targetSum));
}
}
JavaScript
// JavaScript Program to Check if Root to leaf
// path sum equal to a given number
class Node {
constructor(key) {
this.data = key;
this.left = null;
this.right = null;
}
}
// Check if there's a root-to-leaf path
// with the given sum
function hasPathSum(root, targetSum) {
if (root === null) return false;
const stack = [];
const sums = [];
stack.push(root);
sums.push(root.data);
while (stack.length > 0) {
const node = stack.pop();
const sum = sums.pop();
// Check if leaf node and sum matches
if (node.left === null && node.right === null
&& sum === targetSum)
return true;
// Add children to stacks with updated sums
if (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);
}
}
return false;
}
// Construct binary tree
// 10
// / \
// 8 2
// / \ /
// 3 5 2
const root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(5);
root.right.left = new Node(2);
const targetSum = 21;
console.log(hasPathSum(root, targetSum));
Time Complexity: O(n) where n is the number of nodes.
Auxiliary Space: O(h) where h is the height of the tree.
Similar Reads
Root to leaf path sum equal to a given number in BST
Given a Binary Search Tree and a sum target. The task is to check whether the given sum is equal to the sum of all the node from root leaf across any of the root to leaf paths in the given Binary Search Tree.Examples:Input: Output: trueExplanation: root-to-leaf path [1, 3, 4] sums up to the target v
6 min read
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 the 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
8 min read
Root to leaf path product equal to a given number
Given a binary tree and a number, the return is true if the tree has a root-to-leaf path such that the product of all the values along that path equals the given number. The return is false if no such path can be found. For example, in the above tree, there exist three roots to leaf paths with the f
9 min read
Find all root to leaf path sum of a Binary Tree
Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node.
8 min read
Minimize Increments for Equal Path Sum from Root to Any Leaf
Given arrays arr[] and edges[] where edges[i] denotes an undirected edge from edges[i][0] to edges[i][1] and arr[i] represents the value of the ith node. The task is to find the minimum number of increments by 1 required for any node, such that the sum of values along any path from the root to a lea
10 min read
Sum of all the numbers that are formed from root to leaf paths
Given a binary tree, where every node value is a number. Find the sum of all the numbers that are formed from root to leaf paths.Examples:Input: Output: 13997Explanation: There are 4 leaves, hence 4 root to leaf paths:6->3->2 = 6326->3->5->7 = 63576->3->5->4 = 63546->5-
13 min read
Find the maximum sum leaf to root path in a Binary Tree
Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root.Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 and
15+ min read
GCD from root to leaf path in an N-ary tree
Given an N-ary tree and an array val[] which stores the values associated with all the nodes. Also given are a leaf node X and N integers which denotes the value of the node. The task is to find the gcd of all the numbers in the node in the path between leaf to the root. Examples: Input: 1 / \ 2 3 /
7 min read
Root to leaf paths having equal lengths in a Binary Tree
Given a binary tree, print the number of root to leaf paths having equal lengths. Examples: Input : Root of below tree 10 / \ 8 2 / \ / \ 3 5 2 4 Output : 4 paths are of length 3. Input : Root of below tree 10 / \ 8 2 / \ / \ 3 5 2 4 / \ 9 1 Output : 2 paths are of length 3 2 paths are of length 4Re
8 min read
Check if there is a root to leaf path with given sequence
Given a binary tree and an array, the task is to find if the given array sequence is present as a root-to-leaf path in given tree.Examples:Input: arr = {5, 2, 4, 8} Output: TrueExplanation: The given array sequence {5, 2, 4, 8} is present as a root-to-leaf path in given tree.Input: arr = {5, 3, 4, 9
8 min read