Given the root of a binary treeand 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 negativevalues.
[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
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.