VOOZH about

URL: https://www.geeksforgeeks.org/dsa/potd-solutions-20-nov-23-k-sum-paths/

⇱ POTD Solutions | 20 Nov’ 23 | K Sum Paths - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

POTD Solutions | 20 Nov’ 23 | K Sum Paths

Last Updated : 23 Jul, 2025

View all POTD Solutions

Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Trees but will also help you build up problem-solving skills.

👁 20th-november
POTD Solution 20 November 2023
We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.
POTD 20th Nov

Given a binary tree and an integer K. Find the number of paths in the tree which have their sum equal to K. A path may start from any node and end at any node in the downward direction. Since the answer may be very large, compute it modulo 109+7.

Examples:

Input: k = 5
Root of below binary tree:
1
/ \
3 -1
/ \ / \
2 1 4 5
/ / \ \
1 1 2 6

Output: No of paths with sum equals to 5 are: 8
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5

Input: k = 3
1
/ \
2 -1
/ \ /
1 2 3
/ \
2 5

Output: No of paths with sum equals to 3 are : 4

The idea is to use a recursive approach and an unordered map to track running sums. The count is increased when the running sum matches 'k', and it also considers previously encountered sums from the map. The program then explores left and right subtrees, updating the map accordingly.

Step by Step approach:

  • We will be using a unordered map which will be filled with various path sum.
  • For every node we will check if current sum and root’s value equal to k or not. If the sum equals to k then increment the required answer by one.
  • Then we will add all those path sum in map which differs from current sum+root->data value by a constant integer k.
  • Then we will be inserting the current sum + root->data value in the map.
  • We will recursively check for left and right subtrees of current root
  • After the right subtree is also traversed we will remove the current sum + root->data value from the map so that it is not taken into consideration in further traversals of other nodes other than the current root’s

Below is the implementation of the above approach:

Time Complexity: O(N), where N is the number of nodes in the tree
Auxiliary Space: O(N), where N is the number of nodes in the tree

Comment