Path Sum III (LeetCode 437): Solution and Explanation

Medium
Tree
Depth First Search
Binary Tree
Prefix Sum
Hash Table

Given a binary tree and a target, count the downward paths whose values add up to the target. A path can start and end at any node, as long as it only moves from parent to child.

Intuition

The direct approach starts a search at every node and walks down adding values. That works, but a long chain makes it quadratic.

Look at one root-to-node path in isolation. It is just an array, and a downward path ending at the current node is a subarray ending here. The subarray-sum trick applies: if the running sum is curr, a subarray ending here sums to the target exactly when some earlier running sum equals curr - target.

So keep a hash map of running sums seen on the way down from the root. At each node, the number of earlier sums equal to curr - target is the number of valid paths ending at this node. The only twist is that the map must describe the current path only, so a node's sum is removed when the DFS backs out of it.

Approach: Prefix-sum DFS with backtracking

  1. Create a map count with {0: 1}. The 0 stands for the empty prefix above the root, so paths starting at the root are counted.
  2. DFS with the running sum curr. At a node, set curr += node.val.
  3. Add count[curr - targetSum] to the answer: each matching ancestor prefix marks the start of one valid path.
  4. Increment count[curr], recurse into the left and right children, then decrement count[curr] before returning.
  5. Return the accumulated total.

Step-by-step example

root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
  1. Root 10: curr = 10, look up 2, none. Record 10. Node 5: curr = 15, look up 7, none. Record 15.
  2. Node 3 under 5: curr = 18, look up 10, found once, so 5 -> 3 sums to 8. Its children 3 and -2 give 21 and 16, looking up 13 and 8, which are not on their paths.
  3. Node 2 under 5: curr = 17, look up 9, none. Its child 1: curr = 18, look up 10, found, so 5 -> 2 -> 1 sums to 8.
  4. Back at the root, node -3: curr = 7, look up -1, none. Its child 11: curr = 18, look up 10, found, so -3 -> 11 sums to 8.
  5. Every node was visited once and the total is 3.

Code: Python, Java, C++

1class Solution:
2    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
3        count = {0: 1}
4
5        def dfs(node, curr):
6            if not node:
7                return 0
8            curr += node.val
9            found = count.get(curr - targetSum, 0)
10            count[curr] = count.get(curr, 0) + 1
11            found += dfs(node.left, curr) + dfs(node.right, curr)
12            count[curr] -= 1
13            return found
14
15        return dfs(root, 0)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node does one lookup, one insert and one removal in the hash map, all O(1) on average.

Space

O(h)

The recursion and the map only ever hold the current root-to-node path, so both are bounded by the height h of the tree.

Other approaches

Start a search from every node (time O(n^2) worst, O(n log n) balanced, space O(h))

For each node, run a DFS downward that counts paths reaching the target. It is simple and uses no map, but a skewed tree makes it quadratic.

Keep the whole path in a list (time O(n * h), space O(h))

Carry the list of values on the current path and, at each node, walk it backward summing suffixes. Easy to understand, but it is O(n * h).

Common mistakes

  • Forgetting to seed the map with {0: 1}, which drops every path that starts at the root.
  • Not removing a node's prefix after its subtree is done. A sibling branch would then match prefixes from a node that is not its ancestor.
  • Overflow in Java, C++ or C#: values reach 10^9, so the running sum needs a 64-bit type.
  • Recording curr before the lookup when the target is 0. The node would then match itself and count an empty path.

Frequently asked questions

Why does the map start with 0 mapped to 1?

A path from the root to the current node has sum equal to curr. Its 'earlier prefix' is the empty one with sum 0, so 0 must be in the map once from the start.

Why look up before inserting the current sum?

The lookup looks for paths that end at this node and start somewhere above it. If the current sum were already in the map, a target of 0 would count the empty path made of no nodes.

How is this connected to Subarray Sum Equals K?

Every root-to-node path is an array, and this is exactly the subarray-sum counting trick applied along it. The DFS plus the backtracking decrement lets all those arrays share one map.

Can negative values break the method?

No. Prefix-sum counting does not need the values to be positive, unlike a sliding window. Negative values and zeros are handled the same way.