LeetCode #437 Medium

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.
Constraints
  • The number of nodes in the tree is in the range [0, 1000].
  • -10⁹ <= Node.val <= 10⁹
  • -1000 <= targetSum <= 1000
binary treedfsprefix-sum
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
▶3 prefix = {0: 1}
▶4 
▶5 def dfs(node, running):
▶6 if not node:
▶7 return 0
▶8 running += node.val
▶9 count = prefix.get(running - targetSum, 0)
▶10 prefix[running] = prefix.get(running, 0) + 1
▶11 count += dfs(node.left, running) + dfs(node.right, running)
▶12 prefix[running] -= 1
▶13 return count
▶14 
▶15 return dfs(root, 0)
105-332113-21running sums on this path01paths found0store sum 0 once → paths may start at the root
sums{0: 1}the empty start
count0
The table holds the running sums of the nodes above the current one. A path from node A down to node B adds up to B's running sum minus the running sum just above A. Storing 0 once stands for "above the root", so paths that start at the root can be found too.
105-332113-21running sums on this path01101paths found0running sum 10 → need an earlier 2 → none
node10
running10root down to here
look up210 − 8
count0
The sums from the root down to 10 total 10. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 2. The table has no 2, so no path ending here works. Store 10 for the nodes below.
105-332113-21running sums on this path01101151paths found0running sum 15 → need an earlier 7 → none
node5
running15root down to here
look up715 − 8
count0
The sums from the root down to 5 total 15. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 7. The table has no 7, so no path ending here works. Store 15 for the nodes below.
105-332113-21running sums on this path01101151181paths found1running sum 18 → need an earlier 10 → found once
node3
running18root down to here
look up1018 − 8
count1
The sums from the root down to 3 total 18. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 10. The table holds 10 once, so one path ending at 3 count: the green nodes. Then store 18 for the nodes below.
105-332113-21running sums on this path01101151181211paths found1running sum 21 → need an earlier 13 → none
node3
running21root down to here
look up1321 − 8
count1
The sums from the root down to 3 total 21. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 13. The table has no 13, so no path ending here works. Store 21 for the nodes below.
105-332113-21running sums on this path01101151181paths found1leave 3 → remove its sum 21
removed21
count1
Node 3 has no children, so it is done. Its sum 21 is removed, because the next nodes visited are not below 3, and a path must only go downward.
105-332113-21running sums on this path01101151181161paths found1running sum 16 → need an earlier 8 → none
node-2
running16root down to here
look up816 − 8
count1
The sums from the root down to -2 total 16. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 8. The table has no 8, so no path ending here works. Store 16 for the nodes below.
105-332113-21running sums on this path01101151181paths found1leave -2 → remove its sum 16
removed16
count1
Node -2 has no children, so it is done. Its sum 16 is removed, because the next nodes visited are not below -2, and a path must only go downward.
105-332113-21running sums on this path01101151paths found1leave 3 → remove its sum 18
removed18
count1
Everything below 3 is done. Its sum 18 is removed, because the next nodes visited are not below 3, and a path must only go downward.
105-332113-21running sums on this path01101151171paths found1running sum 17 → need an earlier 9 → none
node2
running17root down to here
look up917 − 8
count1
The sums from the root down to 2 total 17. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 9. The table has no 9, so no path ending here works. Store 17 for the nodes below.
105-332113-21running sums on this path01101151171181paths found2running sum 18 → need an earlier 10 → found once
node1
running18root down to here
look up1018 − 8
count2
The sums from the root down to 1 total 18. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 10. The table holds 10 once, so one path ending at 1 count: the green nodes. Then store 18 for the nodes below.
105-332113-21running sums on this path01101151171paths found2leave 1 → remove its sum 18
removed18
count2
Node 1 has no children, so it is done. Its sum 18 is removed, because the next nodes visited are not below 1, and a path must only go downward.
105-332113-21running sums on this path01101151paths found2leave 2 → remove its sum 17
removed17
count2
Everything below 2 is done. Its sum 17 is removed, because the next nodes visited are not below 2, and a path must only go downward.
105-332113-21running sums on this path01101paths found2leave 5 → remove its sum 15
removed15
count2
Everything below 5 is done. Its sum 15 is removed, because the next nodes visited are not below 5, and a path must only go downward.
105-332113-21running sums on this path0110171paths found2running sum 7 → need an earlier -1 → none
node-3
running7root down to here
look up-17 − 8
count2
The sums from the root down to -3 total 7. A downward path ending here adds up to 8 exactly when some node above it had a running sum of -1. The table has no -1, so no path ending here works. Store 7 for the nodes below.
105-332113-21running sums on this path0110171181paths found3running sum 18 → need an earlier 10 → found once
node11
running18root down to here
look up1018 − 8
count3
The sums from the root down to 11 total 18. A downward path ending here adds up to 8 exactly when some node above it had a running sum of 10. The table holds 10 once, so one path ending at 11 count: the green nodes. Then store 18 for the nodes below.
105-332113-21running sums on this path0110171paths found3leave 11 → remove its sum 18
removed18
count3
Node 11 has no children, so it is done. Its sum 18 is removed, because the next nodes visited are not below 11, and a path must only go downward.
105-332113-21running sums on this path01101paths found3leave -3 → remove its sum 7
removed7
count3
Everything below -3 is done. Its sum 7 is removed, because the next nodes visited are not below -3, and a path must only go downward.
105-332113-21running sums on this path01paths found3leave 10 → remove its sum 10
removed10
count3
Everything below the root is done, so its sum 10 is removed too and the search is over.
105-332113-21running sums on this path01paths found3answer: 3
result3
Every node was the bottom end of a lookup exactly once, so each downward path was counted once, from its lowest node. The answer is 3.
05

Common pitfalls

Keeping sums from a finished branch

✗ Wrong
count += dfs(node.left, run) + dfs(node.right, run)
return count
✓ Right
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

✗ Wrong
int running
✓ Right
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

✗ Wrong
prefix = {}
✓ Right
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.

06

Edge cases

Empty tree

dfs(None) returns 0 straight away.

Repeated running sums, e.g. [0, 0] with target 0

The 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.

07

Complexity

Time
O(n)
Space
O(n)
Each node does one lookup, one insert and one removal, each O(1) on average. The map and the recursion hold one entry per node on the current chain, which is O(h), and O(n) for a chain.
08

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.