Given a binary tree and an integer k, count the total number of paths in the tree whose sum of all nodes is equal to k. The path can be any path that is on the root-to-leaf path in the binary tree, or it can be a direct path from the root to a leaf. Alternatively put, a path from node i to node j is valid if i is an ancestor of j.

For example,

Input: Binary Tree:
 
           -8
         /    \
       /        \
      2          7
    /   \      /   \
   8     4   -1     6
        /   /  \     \
       2   7    7     1
 
k = 6
 
Output: 7
 
Explanation: There are 7 paths in the binary tree with a sum of 6, as shown below:
 
-8         2           4         7        -1       -1        6
  \         \         /         /         /          \
   7         4       2        -1         7            7
    \
     6
      \
       1

1. Naive solution

A naive solution is to traverse the binary tree and for every node, check if there is a path starting with it having the sum of all its nodes equal to k. The time complexity of this solution is O(n2), where n is the total number of nodes in the binary tree. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

7

Java


Download  Run Code

Output:

7

Python


Download  Run Code

Output:

7

2. Using Hashing

We can optimize the runtime to O(n) by hashing using a approach similar to finding pairs in an array with a given sum. The idea is to traverse the tree in preorder fashion and keep track of the sum of nodes between the current node and the root node in a variable sum_so_far. We also maintain a map to store the frequency of all possible sums in the current root-to-leaf path. Now if the sum_so_far - k exists in the map, then there must be a path with a sum of nodes equal to k that begins at some node in the current root-to-leaf path and ends at the current node.

Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

7

Java


Download  Run Code

Output:

7

Python


Download  Run Code

Output:

7