Count all K Sum Paths in Binary Tree
Last Updated :
15 Jan, 2025
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: 3
[Naive Approach] By Exploring All Possible Paths – O(n^2) Time and O(h) Space
The simplest approach to solve this problem is that, for each node in the tree, we consider it as the starting point of a path and explore all possible paths that go downward from this node. We calculate the sum of each path and check if it equals k.
C++
//Driver Code Starts{
// C++ Program to Count all K Sum Paths in Binary Tree
// By Exploring All Possible Paths
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int k) {
data = k;
left = nullptr;
right = nullptr;
}
};
//Driver Code Ends }
// Function to count paths with sum k
// starting from the given node
int countPathsFromNode(Node* node, int k, int currentSum) {
if (node == nullptr)
return 0;
int pathCount = 0;
// Update the current sum
currentSum += node->data;
// If current sum equals k, increment path count
if (currentSum == k)
pathCount++;
// Recur for the left and right subtree
pathCount += countPathsFromNode(node->left, k, currentSum);
pathCount += countPathsFromNode(node->right, k, currentSum);
return pathCount;
}
// Function to count all paths that
// sum to k in the binary tree
int countAllPaths(Node* root, int k) {
if (root == nullptr)
return 0;
// Count all paths starting from the current node
int res = countPathsFromNode(root, k, 0);
// Recur for the left and right subtree
res += countAllPaths(root->left, k);
res += countAllPaths(root->right, k);
return res;
}
//Driver Code Starts{
int main() {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node* root = new Node(8);
root->left = new Node(4);
root->right = new Node(5);
root->left->left = new Node(3);
root->left->right = new Node(2);
root->right->right = new Node(2);
root->left->left->left = new Node(3);
root->left->left->right = new Node(-2);
root->left->right->right = new Node(1);
int k = 7;
cout << countAllPaths(root, k) << endl;
return 0;
}
//Driver Code Ends }
C
//Driver Code Starts{
// C Program to Count all K Sum Paths in Binary Tree
// By Exploring All Possible Paths
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* createNode(int k) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = k;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
//Driver Code Ends }
// Function to count paths with sum k starting from the given node
int countPathsFromNode(Node* node, int k, int currentSum) {
if (node == NULL)
return 0;
int pathCount = 0;
// Update the current sum
currentSum += node->data;
// If current sum equals k, increment path count
if (currentSum == k)
pathCount++;
// Recur for the left and right subtree
pathCount += countPathsFromNode(node->left, k, currentSum);
pathCount += countPathsFromNode(node->right, k, currentSum);
return pathCount;
}
// Function to count all paths that sum to k in the binary tree
int countAllPaths(Node* root, int k) {
if (root == NULL)
return 0;
// Count all paths starting from the current node
int res = countPathsFromNode(root, k, 0);
// Recur for the left and right subtree
res += countAllPaths(root->left, k);
res += countAllPaths(root->right, k);
return res;
}
//Driver Code Starts{
int main() {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node* root = createNode(8);
root->left = createNode(4);
root->right = createNode(5);
root->left->left = createNode(3);
root->left->right = createNode(2);
root->right->right = createNode(2);
root->left->left->left = createNode(3);
root->left->left->right = createNode(-2);
root->left->right->right = createNode(1);
int k = 7;
printf("%d
", countAllPaths(root, k));
return 0;
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Java Program to Count all K Sum Paths in Binary Tree
// By Exploring All Possible Paths
import java.util.*;
class Node {
int data;
Node left, right;
Node(int k) {
data = k;
left = null;
right = null;
}
}
class GfG {
//Driver Code Ends }
// Function to count paths with sum k starting from the given node
static int countPathsFromNode(Node node, int k, int currentSum) {
if (node == null)
return 0;
int pathCount = 0;
// Update the current sum
currentSum += node.data;
// If current sum equals k, increment path count
if (currentSum == k)
pathCount++;
// Recur for the left and right subtree
pathCount += countPathsFromNode(node.left, k, currentSum);
pathCount += countPathsFromNode(node.right, k, currentSum);
return pathCount;
}
// Function to count all paths that sum to k in the binary tree
static int countAllPaths(Node root, int k) {
if (root == null)
return 0;
// Count all paths starting from the current node
int res = countPathsFromNode(root, k, 0);
// Recur for the left and right subtree
res += countAllPaths(root.left, k);
res += countAllPaths(root.right, k);
return res;
}
//Driver Code Starts{
public static void main(String[] args) {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
int k = 7;
System.out.println(countAllPaths(root, k));
}
}
//Driver Code Ends }
Python
#Driver Code Starts{
# Python Program to Count all K Sum Paths in Binary Tree
# By Exploring All Possible Paths
class Node:
def __init__(self, k):
self.data = k
self.left = None
self.right = None
#Driver Code Ends }
# Function to count paths with sum k starting from the given node
def countPathsFromNode(node, k, currentSum):
if node is None:
return 0
pathCount = 0
# Update the current sum
currentSum += node.data
# If current sum equals k, increment path count
if currentSum == k:
pathCount += 1
# Recur for the left and right subtree
pathCount += countPathsFromNode(node.left, k, currentSum)
pathCount += countPathsFromNode(node.right, k, currentSum)
return pathCount
# Function to count all paths that sum to k in the binary tree
def countAllPaths(root, k):
if root is None:
return 0
# Count all paths starting from the current node
res = countPathsFromNode(root, k, 0)
# Recur for the left and right subtree
res += countAllPaths(root.left, k)
res += countAllPaths(root.right, k)
return res
#Driver Code Starts{
if __name__ == "__main__":
# Create a sample tree:
# 8
# / \
# 4 5
# / \ \
# 3 2 2
# / \ \
# 3 -2 1
root = Node(8)
root.left = Node(4)
root.right = Node(5)
root.left.left = Node(3)
root.left.right = Node(2)
root.right.right = Node(2)
root.left.left.left = Node(3)
root.left.left.right = Node(-2)
root.left.right.right = Node(1)
k = 7
print(countAllPaths(root, k))
#Driver Code Ends }
C#
//Driver Code Starts{
// C# Program to Count all K Sum Paths in Binary Tree
// By Exploring All Possible Paths
using System;
class Node {
public int data;
public Node left, right;
public Node(int k) {
data = k;
left = null;
right = null;
}
}
class GfG {
//Driver Code Ends }
// Function to count paths with sum k starting from the given node
static int CountPathsFromNode(Node node, int k, int currentSum) {
if (node == null)
return 0;
int pathCount = 0;
// Update the current sum
currentSum += node.data;
// If current sum equals k, increment path count
if (currentSum == k)
pathCount++;
// Recur for the left and right subtree
pathCount += CountPathsFromNode(node.left, k, currentSum);
pathCount += CountPathsFromNode(node.right, k, currentSum);
return pathCount;
}
// Function to count all paths that sum to k in the binary tree
static int CountAllPaths(Node root, int k) {
if (root == null)
return 0;
// Count all paths starting from the current node
int res = CountPathsFromNode(root, k, 0);
// Recur for the left and right subtree
res += CountAllPaths(root.left, k);
res += CountAllPaths(root.right, k);
return res;
}
//Driver Code Starts{
static void Main(string[] args) {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
int k = 7;
Console.WriteLine(CountAllPaths(root, k));
}
}
//Driver Code Ends }
JavaScript
//Driver Code Starts{
// JavaScript Program to Count all K Sum Paths in Binary Tree
// By Exploring All Possible Paths
class Node {
constructor(k) {
this.data = k;
this.left = null;
this.right = null;
}
}
//Driver Code Ends }
// Function to count paths with sum k starting from the given node
function countPathsFromNode(node, k, currentSum) {
if (node === null)
return 0;
let pathCount = 0;
// Update the current sum
currentSum += node.data;
// If current sum equals k, increment path count
if (currentSum === k)
pathCount++;
// Recur for the left and right subtree
pathCount += countPathsFromNode(node.left, k, currentSum);
pathCount += countPathsFromNode(node.right, k, currentSum);
return pathCount;
}
// Function to count all paths that sum to k in the binary tree
function countAllPaths(root, k) {
if (root === null)
return 0;
// Count all paths starting from the current node
let res = countPathsFromNode(root, k, 0);
// Recur for the left and right subtree
res += countAllPaths(root.left, k);
res += countAllPaths(root.right, k);
return res;
}
//Driver Code Starts{
// Driver Code
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
const root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
const k = 7;
console.log(countAllPaths(root, k));
//Driver Code Ends }
[Expected Approach] Using Prefix Sum Technique – O(n) Time and O(n) Space
Prerequisite: The approach is similar to finding subarray with given sum.
To solve this problem, we can use the concept of prefix sums with a hashmap to efficiently track the sum of paths in the binary tree. The prefix sum up to a node is the sum of all node values from the root to that node.
We traverse the tree using recursion and by storing the prefix sums of current path from root in a hashmap, we can quickly find if there are any sub-paths that sum to the target value k by checking the difference between the current prefix sum and k.
If the difference (current prefix sum – k) exists in the hashmap, it means there exists one or more paths, ending at the current node, that sums to k so we increment our count accordingly.
C++
//Driver Code Starts{
// C++ Program to Count all K Sum Paths in Binary Tree
// Using Prefix sum Technique
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Node {
public :
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
//Driver Code Ends }
// Function to find paths in the tree which have
// their sum equal to K
int countPathsUtil(Node* node, int k, int currSum,
unordered_map<int, int>& prefSums) {
if (node == nullptr)
return 0;
int pathCount = 0;
currSum += node->data;
// Pathsum from root to current node is equal to k
if (currSum == k)
pathCount++;
// The count of curr_sum − k gives the number of paths
// with sum k up to the current node
pathCount += prefSums[currSum - k];
// Add the current sum into the hashmap
prefSums[currSum]++;
pathCount += countPathsUtil(node->left, k, currSum, prefSums);
pathCount += countPathsUtil(node->right, k, currSum, prefSums);
// Remove the current sum from the hashmap
prefSums[currSum]--;
return pathCount;
}
// Function to find the paths in the tree which have their
// sum equal to K
int countAllPaths(Node* root, int k) {
unordered_map<int, int> prefSums;
return countPathsUtil(root, k, 0, prefSums);
}
//Driver Code Starts{
int main() {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node* root = new Node(8);
root->left = new Node(4);
root->right = new Node(5);
root->left->left = new Node(3);
root->left->right = new Node(2);
root->right->right = new Node(2);
root->left->left->left = new Node(3);
root->left->left->right = new Node(-2);
root->left->right->right = new Node(1);
int k = 7;
cout << countAllPaths(root, k) << endl;
return 0;
}
//Driver Code Ends }
Java
//Driver Code Starts{
// Java Program to Count all K Sum Paths in Binary Tree
// Using Prefix sum Technique
import java.util.HashMap;
class Node {
int data;
Node left, right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
//Driver Code Ends }
// Function to find paths in the tree which have their sum equal to K
static int countPathsUtil(Node node, int k, int currSum,
HashMap<Integer, Integer> prefSums) {
if (node == null)
return 0;
int pathCount = 0;
currSum += node.data;
// Pathsum from root to current node is equal to k
if (currSum == k)
pathCount++;
// The count of curr_sum − k gives the number of paths
// with sum k up to the current node
pathCount += prefSums.getOrDefault(currSum - k, 0);
// Add the current sum into the hashmap
prefSums.put(currSum, prefSums.getOrDefault(currSum, 0) + 1);
pathCount += countPathsUtil(node.left, k, currSum, prefSums);
pathCount += countPathsUtil(node.right, k, currSum, prefSums);
// Remove the current sum from the hashmap
prefSums.put(currSum, prefSums.get(currSum) - 1);
return pathCount;
}
// Function to find the paths in the tree which have their sum equal to K
static int countAllPaths(Node root, int k) {
HashMap<Integer, Integer> prefSums = new HashMap<>();
return countPathsUtil(root, k, 0, prefSums);
}
//Driver Code Starts{
public static void main(String[] args) {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
int k = 7;
System.out.println(countAllPaths(root, k));
}
}
//Driver Code Ends }
Python
#Driver Code Starts{
# Python Program to Count all K Sum Paths in Binary Tree
# Using Prefix sum Technique
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
#Driver Code Ends }
# Function to find paths in the tree which have their sum equal to K
def countPathsUtil(node, k, currSum, prefSums):
if node is None:
return 0
pathCount = 0
currSum += node.data
# Pathsum from root to current node is equal to k
if currSum == k:
pathCount += 1
# The count of curr_sum − k gives the number of paths
#with sum k up to the current node
pathCount += prefSums.get(currSum - k, 0)
# Add the current sum into the hashmap
prefSums[currSum] = prefSums.get(currSum, 0) + 1
pathCount += countPathsUtil(node.left, k, currSum, prefSums)
pathCount += countPathsUtil(node.right, k, currSum, prefSums)
# Remove the current sum from the hashmap
prefSums[currSum] -= 1
return pathCount
# Function to find the paths in the tree which have their sum equal to K
def countAllPaths(root, k):
prefSums = {}
return countPathsUtil(root, k, 0, prefSums)
#Driver Code Starts{
if __name__ == "__main__":
# Create a sample tree:
# 8
# / \
# 4 5
# / \ \
# 3 2 2
# / \ \
# 3 -2 1
root = Node(8)
root.left = Node(4)
root.right = Node(5)
root.left.left = Node(3)
root.left.right = Node(2)
root.right.right = Node(2)
root.left.left.left = Node(3)
root.left.left.right = Node(-2)
root.left.right.right = Node(1)
k = 7
print(countAllPaths(root, k))
#Driver Code Ends }
C#
//Driver Code Starts{
// C# Program to Count all K Sum Paths in Binary Tree
// Using Prefix sum Technique
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
//Driver Code Ends }
// Function to find paths in the tree which have their sum equal to K
static int CountPathsUtil(Node node, int k, int currSum,
Dictionary<int, int> prefSums) {
if (node == null)
return 0;
int pathCount = 0;
currSum += node.data;
// Pathsum from root to current node is equal to k
if (currSum == k)
pathCount++;
// The count of curr_sum − k gives the number of paths
// with sum k up to the current node
if (prefSums.ContainsKey(currSum - k))
pathCount += prefSums[currSum - k];
// Add the current sum into the hashmap
if (!prefSums.ContainsKey(currSum))
prefSums[currSum] = 0;
prefSums[currSum]++;
pathCount += CountPathsUtil(node.left, k, currSum, prefSums);
pathCount += CountPathsUtil(node.right, k, currSum, prefSums);
// Remove the current sum from the hashmap
prefSums[currSum]--;
return pathCount;
}
// Function to find the paths in the tree which have their sum equal to K
static int CountAllPaths(Node root, int k) {
var prefSums = new Dictionary<int, int>();
return CountPathsUtil(root, k, 0, prefSums);
}
//Driver Code Starts{
static void Main() {
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
Node root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
int k = 7;
Console.WriteLine(CountAllPaths(root, k));
}
}
//Driver Code Ends }
JavaScript
//Driver Code Starts{
// JavaScript Program to Count all K Sum Paths in Binary Tree
// Using Prefix sum Technique
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
//Driver Code Ends }
// Function to find paths in the tree which have their sum equal to K
function countPathsUtil(node, k, currSum, prefSums) {
if (node === null) return 0;
let pathCount = 0;
currSum += node.data;
// Pathsum from root to current node is equal to k
if (currSum === k) pathCount++;
// The count of curr_sum − k gives the number of paths
// with sum k up to the current node
pathCount += prefSums[currSum - k] || 0;
// Add the current sum into the hashmap
prefSums[currSum] = (prefSums[currSum] || 0) + 1;
pathCount += countPathsUtil(node.left, k, currSum, prefSums);
pathCount += countPathsUtil(node.right, k, currSum, prefSums);
// Remove the current sum from the hashmap
prefSums[currSum]--;
return pathCount;
}
// Function to find the paths in the tree which have their sum equal to K
function countAllPaths(root, k) {
const prefSums = {};
return countPathsUtil(root, k, 0, prefSums);
}
//Driver Code Starts{
// Driver Code
// Create a sample tree:
// 8
// / \
// 4 5
// / \ \
// 3 2 2
// / \ \
// 3 -2 1
const root = new Node(8);
root.left = new Node(4);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(2);
root.right.right = new Node(2);
root.left.left.left = new Node(3);
root.left.left.right = new Node(-2);
root.left.right.right = new Node(1);
const k = 7;
console.log(countAllPaths(root, k));
//Driver Code Ends }
Related article:
Similar Reads
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: 3 Table of Content [Naive Approach] By Explori
15+ min read
Print all k-sum paths in a binary tree
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: Inpu
9 min read
Count even paths in Binary Tree
Given a Binary Tree, the task is to count the number of even paths in the given Binary Tree. Even Path is a path where root to leaf path contains all even nodes only. Examples: Input: Below is the given Binary Tree: Output: 3 Explanation: There are 3 even path for the above Binary Tree: 1. 10->12
8 min read
Count of 1's in any path in a Binary Tree
Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.Example: Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4 Approach: A function countUntil has been created which returns the maximum count of 1 in any
10 min read
Count of Fibonacci paths in a Binary tree
Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series. Example: Input: 0 / \ 1 1 / \ / \ 1 10 70 1 / \ 81 2 Output: 2 Explanation: There are 2 Fibonacci pa
10 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 gre
9 min read
Count of exponential paths in a Binary Tree
Given a Binary Tree, the task is to count the number of Exponential paths in the given Binary Tree. Exponential Path is a path where root to leaf path contains all nodes being equal to xy, & where x is a minimum possible positive constant & y is a variable positive integer. Example: Input: 2
11 min read
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
Finding Bitwise AND sum paths in Binary trees
Given a binary tree and a target sum, determine whether there exists a root-to-leaf path in the tree such that the sum of the values of the nodes along the path is equal to the target sum when represented in binary, and the sum of the values of the nodes along the path is calculated by performing a
11 min read
Count Non-Leaf nodes in a Binary Tree
Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
10 min read