Print all k-sum paths in a binary tree
Last Updated :
03 Aug, 2023
A binary tree and a number k are given. Print every path in the tree with sum of the nodes in the path as k.
A path can start from any node and end at any node and must be downward only, i.e. they need not be root node and leaf node; and negative numbers can also be there in the tree.
Examples:
Input : k = 5
Root of below binary tree:
1
/ \
3 -1
/ \ / \
2 1 4 5
/ / \ \
1 1 2 6
Output :
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5
Source : Amazon Interview Experience Set-323
Kindly note that this problem is significantly different from finding k-sum path from root to leaves. Here each node can be treated as root, hence the path can start and end at any node.
Approach:
The basic idea to solve the problem is to do a preorder traversal of the given tree. We also need a container (vector) to keep track of the path that led to that node. At each node we check if there are any path that sums to k, if any we print the path and proceed recursively to print each path.
Code:
Below is the implementation of the same.
C++
// C++ program to print all paths with sum k.
#include <bits/stdc++.h>
using namespace std;
// utility function to print contents of
// a vector from index i to it's end
void printVector(const vector<int>& v, int i)
{
for (int j = i; j < v.size(); j++)
cout << v[j] << " ";
cout << endl;
}
// binary tree node
struct Node {
int data;
Node *left, *right;
Node(int x)
{
data = x;
left = right = NULL;
}
};
// This function prints all paths that have sum k
void printKPathUtil(Node* root, vector<int>& path, int k)
{
// empty node
if (!root)
return;
// add current node to the path
path.push_back(root->data);
// check if there's any k sum path
// in the left sub-tree.
printKPathUtil(root->left, path, k);
// check if there's any k sum path
// in the right sub-tree.
printKPathUtil(root->right, path, k);
// check if there's any k sum path that
// terminates at this node
// Traverse the entire path as
// there can be negative elements too
int f = 0;
for (int j = path.size() - 1; j >= 0; j--) {
f += path[j];
// If path sum is k, print the path
if (f == k)
printVector(path, j);
}
// Remove the current element from the path
path.pop_back();
}
// A wrapper over printKPathUtil()
void printKPath(Node* root, int k)
{
vector<int> path;
printKPathUtil(root, path, k);
}
// Driver code
int main()
{
Node* root = new Node(1);
root->left = new Node(3);
root->left->left = new Node(2);
root->left->right = new Node(1);
root->left->right->left = new Node(1);
root->right = new Node(-1);
root->right->left = new Node(4);
root->right->left->left = new Node(1);
root->right->left->right = new Node(2);
root->right->right = new Node(5);
root->right->right->right = new Node(2);
int k = 5;
printKPath(root, k);
return 0;
}
Java
// Java program to print all paths with sum k.
import java.util.*;
class GFG {
// utility function to print contents of
// a vector from index i to it's end
static void printVector(Vector<Integer> v, int i)
{
for (int j = i; j < v.size(); j++)
System.out.print(v.get(j) + " ");
System.out.println();
}
// binary tree node
static class Node {
int data;
Node left, right;
Node(int x)
{
data = x;
left = right = null;
}
};
static Vector<Integer> path = new Vector<Integer>();
// This function prints all paths that have sum k
static void printKPathUtil(Node root, int k)
{
// empty node
if (root == null)
return;
// add current node to the path
path.add(root.data);
// check if there's any k sum path
// in the left sub-tree.
printKPathUtil(root.left, k);
// check if there's any k sum path
// in the right sub-tree.
printKPathUtil(root.right, k);
// check if there's any k sum path that
// terminates at this node
// Traverse the entire path as
// there can be negative elements too
int f = 0;
for (int j = path.size() - 1; j >= 0; j--) {
f += path.get(j);
// If path sum is k, print the path
if (f == k)
printVector(path, j);
}
// Remove the current element from the path
path.remove(path.size() - 1);
}
// A wrapper over printKPathUtil()
static void printKPath(Node root, int k)
{
path = new Vector<Integer>();
printKPathUtil(root, k);
}
// Driver code
public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(1);
root.left.right.left = new Node(1);
root.right = new Node(-1);
root.right.left = new Node(4);
root.right.left.left = new Node(1);
root.right.left.right = new Node(2);
root.right.right = new Node(5);
root.right.right.right = new Node(2);
int k = 5;
printKPath(root, k);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to print all paths
# with sum k
# utility function to print contents of
# a vector from index i to it's end
def printVector(v, i):
for j in range(i, len(v)):
print(v[j], end=" ")
print()
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# This function prints all paths
# that have sum k
def printKPathUtil(root, path, k):
# empty node
if (not root):
return
# add current node to the path
path.append(root.data)
# check if there's any k sum path
# in the left sub-tree.
printKPathUtil(root.left, path, k)
# check if there's any k sum path
# in the right sub-tree.
printKPathUtil(root.right, path, k)
# check if there's any k sum path that
# terminates at this node
# Traverse the entire path as
# there can be negative elements too
f = 0
for j in range(len(path) - 1, -1, -1):
f += path[j]
# If path sum is k, print the path
if (f == k):
printVector(path, j)
# Remove the current element
# from the path
path.pop(-1)
# A wrapper over printKPathUtil()
def printKPath(root, k):
path = []
printKPathUtil(root, path, k)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(3)
root.left.left = newNode(2)
root.left.right = newNode(1)
root.left.right.left = newNode(1)
root.right = newNode(-1)
root.right.left = newNode(4)
root.right.left.left = newNode(1)
root.right.left.right = newNode(2)
root.right.right = newNode(5)
root.right.right.right = newNode(2)
k = 5
printKPath(root, k)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program to print all paths with sum k.
using System;
using System.Collections.Generic;
class GFG {
// utility function to print contents of
// a vector from index i to it's end
static void printList(List<int> v, int i)
{
for (int j = i; j < v.Count; j++)
Console.Write(v[j] + " ");
Console.WriteLine();
}
// binary tree node
public class Node {
public int data;
public Node left, right;
public Node(int x)
{
data = x;
left = right = null;
}
};
static List<int> path = new List<int>();
// This function prints all paths that have sum k
static void printKPathUtil(Node root, int k)
{
// empty node
if (root == null)
return;
// add current node to the path
path.Add(root.data);
// check if there's any k sum path
// in the left sub-tree.
printKPathUtil(root.left, k);
// check if there's any k sum path
// in the right sub-tree.
printKPathUtil(root.right, k);
// check if there's any k sum path that
// terminates at this node
// Traverse the entire path as
// there can be negative elements too
int f = 0;
for (int j = path.Count - 1; j >= 0; j--) {
f += path[j];
// If path sum is k, print the path
if (f == k)
printList(path, j);
}
// Remove the current element from the path
path.RemoveAt(path.Count - 1);
}
// A wrapper over printKPathUtil()
static void printKPath(Node root, int k)
{
path = new List<int>();
printKPathUtil(root, k);
}
// Driver code
public static void Main(String[] args)
{
Node root = new Node(1);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(1);
root.left.right.left = new Node(1);
root.right = new Node(-1);
root.right.left = new Node(4);
root.right.left.left = new Node(1);
root.right.left.right = new Node(2);
root.right.right = new Node(5);
root.right.right.right = new Node(2);
int k = 5;
printKPath(root, k);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
// Tree node class for Binary Tree
// representation
class Node {
constructor(data) {
this.data = data;
this.left = this.right = null;
}
}
function printPathUtil(node, k, path_arr, all_path_arr) {
if (node == null) {
return;
}
let p1 = node.data.toString();
let p2 = '';
if (path_arr.length > 0) {
p2 = path_arr + ',' + p1;
}
else {
p2 = p1;
}
if (node.data == k) {
all_path_arr.add(p1);
}
let sum = 0;
let p2_arr = p2.split(',');
for (let i = 0; i < p2_arr.length; i++) {
sum = sum + Number(p2_arr[i]);
}
if (sum == k) {
all_path_arr.add(p2);
}
printPathUtil(node.left, k, p1, all_path_arr)
printPathUtil(node.left, k, p2, all_path_arr)
printPathUtil(node.right, k, p1, all_path_arr)
printPathUtil(node.right, k, p2, all_path_arr)
}
function printKPath(root, k) {
let all_path_arr = new Set();
printPathUtil(root, k, '', all_path_arr);
return all_path_arr;
}
function printPaths(paths) {
for (let data of paths) {
document.write(data.replaceAll(',', ' '));
document.write('<br>');
}
}
// Driver code
let root = new Node(1);
root.left = new Node(3);
root.left.left = new Node(2);
root.left.right = new Node(1);
root.left.right.left = new Node(1);
root.right = new Node(-1);
root.right.left = new Node(4);
root.right.left.left = new Node(1);
root.right.left.right = new Node(2);
root.right.right = new Node(5);
root.right.right.right = new Node(2);
let k = 5;
printPaths(printKPath(root, k));
// This code is contributed by gaurav2146
Output3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5
Time complexity: O(N^2), where N is the number of nodes in the binary tree. This is because for each node, we traverse the entire path (up to N nodes) to check if there exists a path with a sum equal to k.
Auxiliary space: O(N) because in the worst case, the path vector can store up to N nodes. Additionally, the recursive calls consume stack space proportional to the height of the tree, which can be at most N in the case of a skewed tree.
This article is contributed by Ashutosh Kumar
Similar Reads
Print all K-sum levels in a Binary Tree
Given a Binary Tree and an integer K where the tree has positive and negative nodes, the task is to print the elements of the level whose sum equals K. If no such result exists, then print "Not Possible". Examples: Input: -10 / \ 2 -3 / \ \ 4 15 -6 / \ / 7 -8 9 K = 13 Output: 4 15 -6 Explanation: Le
8 min read
Count all K Sum Paths in Binary Tree
Given a binary tree and an integer k, the task is to count the number of paths in the tree such that the sum of the nodes in each path equals k. A path can start from any node and end at any node and must be downward only.Examples:Input: k = 7 Output: 3Table of Content[Naive Approach] By Exploring A
15+ 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
Sum of all nodes in a binary tree
Give an algorithm for finding the sum of all elements in a binary tree. In the above binary tree sum = 106. Recommended PracticeSum of Binary TreeTry It!The idea is to recursively, call left subtree sum, right subtree sum and add their values to current node's data. Implementation: C++ /* Program to
15+ min read
Print Root-to-Leaf Paths in a Binary Tree
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.Example:Input:Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perform
2 min read
Maximum Path Sum in a Binary Tree
Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree.Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree.Input: Output: 31Explanation: Max path sum is represented using green
8 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
7 min read
Sum of all pair shortest paths in a Tree
Given a weighted undirected graph T consisting of nodes valued [0, N - 1] and an array Edges[][3] of type {u, v, w} that denotes an edge between vertices u and v having weight w. The task is to find the sum of all pair shortest paths in the given tree. Examples: Input: N = 3, Edges[][] = {{0, 2, 15}
15+ min read
Find sum of all right leaves in a given Binary Tree
Given a Binary Tree, the task is to find the sum of all right leaf nodes in it. Examples : Example1: Sum of all the right leaf nodes in the below tree is 2 + 5 + 7 = 15 Example2: Sum of all the right leaf nodes in the below tree is 5 + 8 = 13 Table of Content [Expected Approach - 1] Using Recursion
14 min read
Print all the paths from root, with a specified sum in Binary tree
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 s
8 min read