Open In App

Count all K Sum Paths in Binary Tree

Last Updated : 15 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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

Tree

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++


// 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;
}


C Java Python C# JavaScript

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.


C++


// 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);
}


Java Python C# JavaScript

Output
3

Related article:




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg