Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum. Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node.
Examples:
Input:
Output: [[1, 3, 4]] Explanation: The below image shows the path starting from the root that sums upto the given sum
Input:
Output: [[10, 28], [10, 13, 15]] Explanation: The below image shows the path starting from the root that sums upto the given sum
[Using DFS + Backtracking] - O(n²) Time and O(h) Space
We use DFS with backtracking to explore all root-to-node paths. While traversing, we maintain the current sum and path. Whenever the sum equals the target, we store that path. After exploring each node, we backtrackto explore other potential paths.
Start DFS traversal from root
Maintain a vector path and variable sum_so_far
Add current node value and If sum_so_far == target, store the current path
Recur for left and right subtrees.
Backtrack by removing last element from path
C++
#include<iostream>#include<vector>usingnamespacestd;// Given Node structureclassNode{public:intkey;Node*left,*right;Node(intx){left=right=nullptr;key=x;}};// Utility functionvoidprintPathsUtil(Node*curr,intsum,intcurrSum,vector<int>&path,vector<vector<int>>&ans){if(curr==nullptr)return;// Add current nodecurrSum+=curr->key;path.push_back(curr->key);// If sum matches → store pathif(currSum==sum){ans.push_back(path);}// Recur left and rightprintPathsUtil(curr->left,sum,currSum,path,ans);printPathsUtil(curr->right,sum,currSum,path,ans);// Backtrackpath.pop_back();}// Function to return all pathsvector<vector<int>>printPaths(Node*root,intsum){vector<vector<int>>ans;vector<int>path;printPathsUtil(root,sum,0,path,ans);returnans;}// Driver codeintmain(){Node*root=newNode(1);root->left=newNode(20);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(15);root->right->left->left=newNode(6);intsum=8;vector<vector<int>>result=printPaths(root,sum);for(auto&path:result){for(intval:path){cout<<val<<" ";}cout<<endl;}return0;}
Java
importjava.util.ArrayList;importjava.util.List;// Given Node structureclassNode{publicintkey;publicNodeleft,right;publicNode(intx){left=right=null;key=x;}}// Utility functionpublicclassMain{publicstaticvoidprintPathsUtil(Nodecurr,intsum,intcurrSum,List<Integer>path,List<List<Integer>>ans){if(curr==null)return;// Add current nodecurrSum+=curr.key;path.add(curr.key);// If sum matches → store pathif(currSum==sum){ans.add(newArrayList<>(path));}// Recur left and rightprintPathsUtil(curr.left,sum,currSum,path,ans);printPathsUtil(curr.right,sum,currSum,path,ans);// Backtrackpath.remove(path.size()-1);}// Function to return all pathspublicstaticList<List<Integer>>printPaths(Noderoot,intsum){List<List<Integer>>ans=newArrayList<>();List<Integer>path=newArrayList<>();printPathsUtil(root,sum,0,path,ans);returnans;}// Driver codepublicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(20);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(15);root.right.left.left=newNode(6);intsum=8;List<List<Integer>>result=printPaths(root,sum);for(List<Integer>path:result){for(intval:path){System.out.print(val+" ");}System.out.println();}}}
Python
classNode:def__init__(self,x):self.key=xself.left=Noneself.right=NonedefprintPathsUtil(curr,target,currSum,path,res):ifcurrisNone:return# Add current nodecurrSum+=curr.keypath.append(curr.key)# If sum matches, store pathifcurrSum==target:res.append(path[:])# Recur left and rightprintPathsUtil(curr.left,target,currSum,path,res)printPathsUtil(curr.right,target,currSum,path,res)# Backtrackpath.pop()defprintPaths(root,target):res=[]path=[]printPathsUtil(root,target,0,path,res)returnresroot=Node(1)root.left=Node(20)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(15)root.right.left.left=Node(6)target=8res=printPaths(root,target)forpathinres:print(*path)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintkey;publicNodeleft,right;publicNode(intx){key=x;left=right=null;}}classGfG{staticvoidPrintPathsUtil(Nodecurr,intsum,intcurrSum,List<int>path,List<List<int>>res){if(curr==null)return;// Add current nodecurrSum+=curr.key;path.Add(curr.key);// If sum matches, store pathif(currSum==sum){res.Add(newList<int>(path));}// Recur left and rightPrintPathsUtil(curr.left,sum,currSum,path,res);PrintPathsUtil(curr.right,sum,currSum,path,res);// Backtrackpath.RemoveAt(path.Count-1);}staticList<List<int>>PrintPaths(Noderoot,intsum){List<List<int>>res=newList<List<int>>();List<int>path=newList<int>();PrintPathsUtil(root,sum,0,path,res);returnres;}staticvoidMain(){Noderoot=newNode(1);root.left=newNode(20);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(15);root.right.left.left=newNode(6);intsum=8;List<List<int>>res=PrintPaths(root,sum);foreach(List<int>pathinres){foreach(intxinpath){Console.Write(x+" ");}Console.WriteLine();}}}
JavaScript
classNode{constructor(x){this.key=x;this.left=null;this.right=null;}}functionprintPathsUtil(curr,target,currSum,path,res){if(curr===null)return;// Add current nodecurrSum+=curr.key;path.push(curr.key);// If sum matches, store pathif(currSum===target){res.push([...path]);}// Recur left and rightprintPathsUtil(curr.left,target,currSum,path,res);printPathsUtil(curr.right,target,currSum,path,res);// Backtrackpath.pop();}functionprintPaths(root,target){letres=[];letpath=[];printPathsUtil(root,target,0,path,res);returnres;}letroot=newNode(1);root.left=newNode(20);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(15);root.right.left.left=newNode(6);lettarget=8;letres=printPaths(root,target);for(letpathofres){console.log(...path);}