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 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.
// 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;
}
// 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;
}
// 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;
}
# 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
// 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;
}
// 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;
}
Output
3
[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.


































// 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);
}
// 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);
}
# 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)
// 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);
}
// 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);
}
Output
3
Related article: