Root to leaf path sum equal to a given number
Last Updated :
23 Jul, 2025
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.
Root to leaf path sum equal to a given number
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem