VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-all-k-sum-paths-in-a-binary-tree/

⇱ Count all K Sum Paths in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count all K Sum Paths in Binary Tree

Last Updated : 4 Oct, 2025

Given the root of a binary tree and an integer k, 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.
Note: The nodes can have negative values.

Examples:

Input: k = 7

👁 420046697

Output: 3
Explanation:

👁 4200466971

Input: k = 7

👁 420046771


Output: 3
Explanation:

👁 420046697

[Naive Approach] By Exploring All Possible Paths - O(n2) 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.


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.

We can use 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.



Output
3
Comment
Article Tags: