Path Sum III
Path Sum III is LeetCode 437 (Medium). Given the root of a binary tree and an integer targetSum, return how many paths have values that add up to targetSum.
- A path goes downward only, from a node to one of its descendants, but it may start and end at any node, not just at the root or a leaf.
- Values go up to ±10⁹ across 1,000 nodes, so running sums can pass the 32-bit integer range.
- The number of nodes in the tree is in the range [0, 1000].
- -10⁹ <= Node.val <= 10⁹
- -1000 <= targetSum <= 1000
Intuition
Treat the chain from the root to the current node like an array and use prefix sums. Let run be the sum of the values from the root down to the current node. A downward path ending here adds up to the target exactly when some node above it had a running sum of run − targetSum: the path is everything below that node.
So keep a hash map that counts the running sums on the current chain, and one lookup finds every valid path that ends at the current node. The map must hold only the current chain, so a node's sum is removed when the search leaves that node.
"Count paths or subarrays that add up to k" is a prefix-sum count. On a tree the prefix is the root-to-node chain, so entries are added on the way down and removed on the way back.
Approach
Before reading on, write the sum of a downward path from node A to node B using two running sums from the root. Then decide what must be stored so that, at B, one lookup counts every valid A. Aim for O(n).
Seed the map with 0
Start with prefix = {0: 1}. It stands for the empty sum above the root, so a path that starts at the root is found when run − targetSum is 0.
Look up, then store
At each node, add its value to run, add prefix[run − targetSum] to the count, and only then increase prefix[run]. Looking up first stops a node from being paired with itself, which with a target of 0 would count an empty path at every node.
Recurse, then remove the sum
Visit the left and right children with the new run, then decrease prefix[run]. The nodes visited next are not below this one, so this sum must stop being a possible starting point.
Why each path is counted once
A downward path has one lowest node. It is counted at that node's lookup, through the running sum of the node just above its top, and at no other lookup. Adding the counts from all nodes gives the answer.
Code in Python, C++ and Java
Common pitfalls
Keeping sums from a finished branch
count += dfs(node.left, run) + dfs(node.right, run) return count
count += dfs(node.left, run) + dfs(node.right, run) prefix[run] -= 1 return count
For [2, 3, 4] with target 1, node 3 stores sum 5. If it stays, node 4 (running sum 6) looks up 6 − 1 = 5 and counts a path, but 3 is not above 4. The answer is 0, not 1.
32-bit running sums in C++ or Java
int running
long long running // long in Java
For [1000000000, 1000000000, null, 294967296, null, 1000000000, null, 1000000000, null, 1000000000] with target 0, the int sum wraps around to 0 after three nodes, and the C++ int version returns 2 instead of 0. Python integers do not overflow.
Forgetting the 0 seed
prefix = {}prefix = {0: 1}A path that starts at the root has no node above it to subtract. For [5] with target 5, the lookup for 0 finds nothing and the answer comes out 0 instead of 1.
Edge cases
dfs(None) returns 0 straight away.
[0, 0] with target 0The map stores how many times each sum appears, so the child finds 0 twice. The answer is 3: each zero on its own and both together.
Complexity
Path Sum III FAQ
Is the O(n²) double recursion good enough?
Starting a downward count from every node is the usual first idea and costs O(n · h): about n log n on a balanced tree and n² on a chain. With at most 1,000 nodes it passes, but the prefix-sum version is O(n) and is the answer interviewers look for.
How is this related to Subarray Sum Equals K?
It is the same idea on a tree. In Subarray Sum Equals K (LeetCode 560) the prefix sums of an array go into a map and stay there. Here the "array" is the root-to-node chain, so a sum has to leave the map when the search backs out of its node.