Print all the paths from root to leaf, with a specified sum in Binary tree
Last Updated : 23 Jul, 2025
Given a Binary tree and target sum, the task is to find all the possible paths from root to leaf that have the sum equal to the given sum.
Examples
Input:
Output: [[10, 28]] Explanation: Paths [[10, 28]] sum to 38.
Input:
Output: [] Explanation: No root-to-leaf path sums to 8, so the output is empty.
Approach:
The idea is to traverse the binary tree using DFS traversal from the root to all the leaf nodes, keeping track of the current path and the remaining sum. For each node, subtract its value from the target sum and continue the search in the left and right subtrees. When a leaf node is reached and the sum is zero, the path is valid and is stored.
C++
// C++ Program to print all Root to Leaf paths// with a sum equal to a given number#include<bits/stdc++.h>usingnamespacestd;classNode{public:Node*left,*right;intdata;Node(intx){data=x;left=nullptr;right=nullptr;}};// Helper function to find paths with the given sumvoidfindPaths(Node*root,intsum,vector<int>&path,vector<vector<int>>&result){if(root==nullptr){return;}// Add current node's data to the pathpath.push_back(root->data);// Check if the current node is a leaf and // sum equals its valueif(root->left==nullptr&&root->right==nullptr&&sum==root->data){result.push_back(path);}else{// Otherwise, check in the left and // right subtreesfindPaths(root->left,sum-root->data,path,result);findPaths(root->right,sum-root->data,path,result);}// Backtrack to explore other pathspath.pop_back();}// Function to find and return all paths // with the given sumvector<vector<int>>PathsWithSum(Node*root,intsum){vector<int>path;vector<vector<int>>result;findPaths(root,sum,path,result);returnresult;}voidprint2DArray(vector<vector<int>>&arr){for(auto&row:arr){for(intval:row){cout<<val<<" ";}cout<<endl;}}intmain(){// Constructed binary tree is// 10// / \ // 1 2// / \ \ // 4 5 3 Node*root=newNode(10);root->left=newNode(1);root->right=newNode(2);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(3);intsum=15;vector<vector<int>>paths=PathsWithSum(root,sum);print2DArray(paths);return0;}
Java
// Java Program to print all Root to Leaf paths// with a sum equal to a given numberimportjava.util.*;classNode{Nodeleft,right;intdata;Node(intx){data=x;left=null;right=null;}}classGfG{// Helper function to find paths with the given sumstaticvoidfindPaths(Noderoot,intsum,List<Integer>path,List<List<Integer>>result){if(root==null){return;}// Add current node's data to the pathpath.add(root.data);// Check if the current node is a leaf and // sum equals its valueif(root.left==null&&root.right==null&&sum==root.data){result.add(newArrayList<>(path));}else{// Otherwise, check in the left and // right subtreesfindPaths(root.left,sum-root.data,path,result);findPaths(root.right,sum-root.data,path,result);}// Backtrack to explore other pathspath.remove(path.size()-1);}// Function to find and return all paths // with the given sumstaticList<List<Integer>>PathsWithSum(Noderoot,intsum){List<Integer>path=newArrayList<>();List<List<Integer>>result=newArrayList<>();findPaths(root,sum,path,result);returnresult;}staticvoidprint2DArray(List<List<Integer>>arr){for(List<Integer>row:arr){for(intval:row){System.out.print(val+" ");}System.out.println();}}publicstaticvoidmain(String[]args){// Constructed binary tree is// 10// / \// 1 2// / \ \// 4 5 3 Noderoot=newNode(10);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(3);intsum=15;List<List<Integer>>paths=PathsWithSum(root,sum);print2DArray(paths);}}
Python
# Python program to print all Root to Leaf paths# with a sum equal to a given numberclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Helper function to find paths with the given sumdeffindPaths(root,sum,path,result):ifrootisNone:return# Add current node's data to the pathpath.append(root.data)# Check if the current node is a leaf and # sum equals its valueifroot.leftisNoneandroot.right \
isNoneandsum==root.data:result.append(list(path))else:# Otherwise, check in the left and # right subtreesfindPaths(root.left,sum-root.data,path,result)findPaths(root.right,sum-root.data,path,result)# Backtrack to explore other pathspath.pop()# Function to find and return all paths with the given sumdefpathsWithSum(root,sum):path=[]result=[]findPaths(root,sum,path,result)returnresultdefprint2DArray(arr):forrowinarr:print(" ".join(map(str,row)))if__name__=="__main__":# Constructed binary tree is# 10# / \# 1 2# / \ \# 4 5 3 root=Node(10)root.left=Node(1)root.right=Node(2)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(3)sum=15paths=pathsWithSum(root,sum)print2DArray(paths)
C#
// C# Program to print all Root to Leaf paths// with a sum equal to a given numberusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Helper function to find paths with the given sumstaticvoidFindPaths(Noderoot,intsum,List<int>path,List<List<int>>result){if(root==null){return;}// Add current node's data to the pathpath.Add(root.data);// Check if the current node is a leaf and // sum equals its valueif(root.left==null&&root.right==null&&sum==root.data){result.Add(newList<int>(path));}else{// Otherwise, check in the left and // right subtreesFindPaths(root.left,sum-root.data,path,result);FindPaths(root.right,sum-root.data,path,result);}// Backtrack to explore other pathspath.RemoveAt(path.Count-1);}// Function to find and return all paths // with the given sumstaticList<List<int>>PathsWithSum(Noderoot,intsum){List<int>path=newList<int>();List<List<int>>result=newList<List<int>>();FindPaths(root,sum,path,result);returnresult;}staticvoidPrint2DArray(List<List<int>>arr){foreach(varrowinarr){foreach(intvalinrow){Console.Write(val+" ");}Console.WriteLine();}}staticvoidMain(string[]args){// Constructed binary tree is// 10// / \// 1 2// / \ \// 4 5 3 Noderoot=newNode(10);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(3);intsum=15;List<List<int>>paths=PathsWithSum(root,sum);Print2DArray(paths);}}
JavaScript
// JavaScript program to print all Root to Leaf paths// with a sum equal to a given numberclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Helper function to find paths with the given sumfunctionfindPaths(root,sum,path,result){if(root===null){return;}// Add current node's data to the pathpath.push(root.data);// Check if the current node is a leaf and// sum equals its valueif(root.left===null&&root.right===null&&sum===root.data){result.push([...path]);}else{// Otherwise, check in the left and// right subtreesfindPaths(root.left,sum-root.data,path,result);findPaths(root.right,sum-root.data,path,result);}// Backtrack to explore other pathspath.pop();}// Function to find and return all paths // with the given sumfunctionpathsWithSum(root,sum){letpath=[];letresult=[];findPaths(root,sum,path,result);returnresult;}functionprint2DArray(arr){arr.forEach(row=>{console.log(row.join(" "));});}// Constructed binary tree is// 10// / \// 1 2// / \ \// 4 5 3letroot=newNode(10);root.left=newNode(1);root.right=newNode(2);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(3);letsum=15;letpaths=pathsWithSum(root,sum);print2DArray(paths);
Output
10 1 4
10 2 3
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once. Auxiliary Space: O(h), where h is the height of the tree, due to the recursion stack and path storage.