Open In App

Count all K Sum Paths in Binary Tree

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
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++
//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 }

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

Output
3

Related article:




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg