Print all the paths from root, with a specified sum in Binary tree
Last Updated :
02 Dec, 2024
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
Approach:
The idea is to find all paths starting from the root of the binary tree whose sum equals the given target. We traverse the tree recursively, maintaining a running sum and a list of nodes forming the current path. Whenever the running sum matches the target, the current path is saved. After exploring each node, we backtrack to explore other potential paths.
C++
// C++ program to print all paths beginning with
// root and sum as given sum
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Utility function to find all paths with a given sum
void printPathsUtil(Node* curr, int sum, int currsum,
vector<int>& path, vector<vector<int>>& ans) {
if (curr == nullptr) {
return;
}
// Add current node's value to the running
// sum and path
currsum += curr->data;
path.push_back(curr->data);
// If the path sum equals the target,
// store the path
if (currsum == sum) {
ans.push_back(path);
}
// Recursively check left and right subtrees
if (curr->left != nullptr) {
printPathsUtil(curr->left, sum,
currsum, path, ans);
}
if (curr->right != nullptr) {
printPathsUtil(curr->right, sum,
currsum, path, ans);
}
// Backtrack to explore other paths
path.pop_back();
}
// Function to find all paths with a given sum
vector<vector<int>> printPaths(Node* root, int sum) {
vector<int> path;
vector<vector<int>> ans;
printPathsUtil(root, sum, 0, path, ans);
return ans;
}
void print2DArray(vector<vector<int>>& result) {
for (auto& path : result) {
for (int val : path) {
cout << val << " ";
}
cout << endl;
}
}
int main() {
// Representation of given Binary Tree
// 1
// / \
// 20 3
// / \
// 4 15
// /
// 6
Node* root = new Node(1);
root->left = new Node(20);
root->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(15);
root->right->left->left = new Node(6);
int sum = 8;
vector<vector<int>> result
= printPaths(root, sum);
print2DArray(result);
return 0;
}
Java
// Java program to print all paths beginning
// with root and sum as given sum
import java.util.*;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Utility function to find all paths with a given sum
static void printPathsUtil(Node curr, int sum, int currsum,
ArrayList<Integer> path,
ArrayList<ArrayList<Integer>> ans) {
if (curr == null) {
return;
}
// Add current node's value to the running
// sum and path
currsum += curr.data;
path.add(curr.data);
// If the path sum equals the target,
// store the path
if (currsum == sum) {
ans.add(new ArrayList<>(path));
}
// Recursively check left and right subtrees
if (curr.left != null) {
printPathsUtil(curr.left, sum, currsum, path, ans);
}
if (curr.right != null) {
printPathsUtil(curr.right, sum, currsum, path, ans);
}
// Backtrack to explore other paths
path.remove(path.size() - 1);
}
// Function to find all paths with a given sum
static ArrayList<ArrayList<Integer>> printPaths(Node root, int sum) {
ArrayList<Integer> path = new ArrayList<>();
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
printPathsUtil(root, sum, 0, path, ans);
return ans;
}
static void print2DArray(ArrayList<ArrayList<Integer>> result) {
for (ArrayList<Integer> path : result) {
for (int val : path) {
System.out.print(val + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// Representation of given Binary Tree
// 1
// / \
// 20 3
// / \
// 4 15
// /
// 6
Node root = new Node(1);
root.left = new Node(20);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(15);
root.right.left.left = new Node(6);
int sum = 8;
ArrayList<ArrayList<Integer>> result
= printPaths(root, sum);
print2DArray(result);
}
}
Python
# Python program to Print all the
# paths from root, with a specified
# sum in Binary tree
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to find all paths with a given sum
def printPathsUtil(curr, targetSum, currSum, path, ans):
if curr is None:
return
# Add current node's value to the running
# sum and path
currSum += curr.data
path.append(curr.data)
# If the path sum equals the target,
# store the path
if currSum == targetSum:
ans.append(list(path))
# Recursively check left and right subtrees
if curr.left is not None:
printPathsUtil(curr.left, targetSum, currSum, path, ans)
if curr.right is not None:
printPathsUtil(curr.right, targetSum, currSum, path, ans)
# Backtrack to explore other paths
path.pop()
# Function to find all paths with a given sum
def printPaths(root, targetSum):
path = []
ans = []
printPathsUtil(root, targetSum, 0, path, ans)
return ans
def print2DArray(result):
for path in result:
print(" ".join(map(str, path)))
if __name__ == '__main__':
# Representation of the binary tree
# 1
# / \
# 20 3
# / \
# 4 15
# /
# 6
root = 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)
targetSum = 8
result = printPaths(root, targetSum)
print2DArray(result)
C#
// C# program to print all paths beginning
// with root and sum as given sum
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Utility function to find all paths with a given sum
static void PrintPathsUtil(Node curr, int sum, int currsum,
List<int> path,
List<List<int>> ans) {
if (curr == null) {
return;
}
// Add current node's value to the running
// sum and path
currsum += curr.data;
path.Add(curr.data);
// If the path sum equals the target,
// store the path
if (currsum == sum) {
ans.Add(new List<int>(path));
}
// Recursively check left and right subtrees
if (curr.left != null) {
PrintPathsUtil(curr.left, sum, currsum, path, ans);
}
if (curr.right != null) {
PrintPathsUtil(curr.right, sum, currsum, path, ans);
}
// Backtrack to explore other paths
path.RemoveAt(path.Count - 1);
}
// Function to find all paths with a given sum
static List<List<int>> PrintPaths(Node root, int sum) {
List<int> path = new List<int>();
List<List<int>> ans = new List<List<int>>();
PrintPathsUtil(root, sum, 0, path, ans);
return ans;
}
static void Print2DArray(List<List<int>> result) {
foreach (var path in result) {
foreach (var val in path) {
Console.Write(val + " ");
}
Console.WriteLine();
}
}
static void Main(string[] args) {
// Representation of given Binary Tree
// 1
// / \
// 20 3
// / \
// 4 15
// /
// 6
Node root = new Node(1);
root.left = new Node(20);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(15);
root.right.left.left = new Node(6);
int sum = 8;
List<List<int>> result = PrintPaths(root, sum);
Print2DArray(result);
}
}
JavaScript
// Javascript program to print all paths beginning
// with root and sum as given sum
class Node {
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// Utility function to find all paths with a given sum
function printPathsUtil(curr, sum, currSum, path, ans) {
if (curr === null) {
return;
}
// Add current node's value to the running sum and path
currSum += curr.data;
path.push(curr.data);
// If the path sum equals the target, store the path
if (currSum === sum) {
ans.push([...path]);
}
// Recursively check left and right subtrees
if (curr.left !== null) {
printPathsUtil(curr.left, sum, currSum, path, ans);
}
if (curr.right !== null) {
printPathsUtil(curr.right, sum, currSum, path, ans);
}
// Backtrack to explore other paths
path.pop();
}
// Function to find all paths with a given sum
function printPaths(root, sum) {
const path = [];
const ans = [];
printPathsUtil(root, sum, 0, path, ans);
return ans;
}
function print2DArray(result) {
for (const path of result) {
console.log(path.join(" "));
}
}
// Representation of given Binary Tree
// 1
// / \
// 20 3
// / \
// 4 15
// /
// 6
const root = new Node(1);
root.left = new Node(20);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(15);
root.right.left.left = new Node(6);
const sum = 8;
const result = printPaths(root, sum);
print2DArray(result);
Time Complexity: O(n * h), where n is the number of nodes in the tree, and h is the height of the tree.
Auxiliary Space: O(h), where h is the height of the tree.