LeetCode #113 Medium

Path Sum II

Path Sum II is LeetCode 113 (Medium). Given the root of a binary tree and an integer targetSum, return every root-to-leaf path whose node values add up to targetSum, each as a list of values.

  • A leaf is a node with no children. A path must start at the root and end at a leaf.
  • Values and the target can be negative, so a running sum that overshoots can still come back.
  • The tree may be empty, and it can be a 5,000-node chain.
Constraints
  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
binary treedfsbacktracking
Open on LeetCode ↗
02

Intuition

Walk the tree depth-first with one shared path list: push a node when you step into it and pop it when you leave. At every moment the list holds exactly the values from the root down to the current node, so reaching a leaf with nothing left to find means the list is an answer.

  • Remaining target: subtract each value on the way down, so the test at a leaf is a single comparison with 0.
  • Copy on save: the list keeps changing after a match, so the answer stores a snapshot of it.
  • Pop on the way out: removing the node gives the parent back its own path for the next branch.
How to spot this pattern

"Return every path" in a tree is DFS with backtracking: one list grows as you go down, shrinks as you come back, and is copied whenever it forms a full answer.

03

Approach

Try it first

Before reading on, decide what state each recursive call needs, what exactly makes a path count, and what you must undo before returning to the parent. Aim for one visit per node.

1

Step into a node

Append node.val to path and subtract it from remaining. Because remaining is a plain number passed into each call, every call has its own copy, and the parent's value is unchanged when the call returns.

2

Save a copy at a matching leaf

If the node has no children and remaining == 0, the list is a full root-to-leaf path with the right total. Append path[:] (a new list), not path, to the result.

3

Go left, then right

Recurse into each child that exists, left first. Leaves are then reached in left-to-right order, so the saved paths come out in the same order as the examples.

4

Pop before returning

After both children are done, remove the last value with path.pop(), whether or not anything matched. The list is then exactly what the parent had, so its other branch starts from the right prefix.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
▶3 res, path = [], []
▶4 
▶5 def dfs(node, remaining):
▶6 path.append(node.val)
▶7 remaining -= node.val
▶8 if not node.left and not node.right and remaining == 0:
▶9 res.append(path[:])
▶10 if node.left:
▶11 dfs(node.left, remaining)
▶12 if node.right:
▶13 dfs(node.right, remaining)
▶14 path.pop()
▶15 
▶16 if root:
▶17 dfs(root, targetSum)
▶18 return res
123413path1still need6paths savednone yetadd 1 to the path → still need 6
node1
remaining6
path[1]
Step into node 1: push it onto the path and subtract it, so the path 1 still needs 6. Node 1 has children, so the path is not finished yet; try them left first.
123413path12still need4paths savednone yetadd 2 to the path → still need 4
node2
remaining4
path[1, 2]
Step into node 2: push it onto the path and subtract it, so the path 1, 2 still needs 4. Node 2 has children, so the path is not finished yet; try them left first.
123413path124still need0paths savednone yetadd 4 to the path → still need 0
node4
remaining0
path[1, 2, 4]
Step into node 4: push it onto the path and subtract it, so the path 1, 2, 4 still needs 0. Node 4 has no children, so this is a full root-to-leaf path and can be checked.
123413path124still need0paths saved124leaf and need 0 → save a copy of the path
remaining0
saved1
A leaf with nothing left to find: 1, 2, 4 adds up to 7. Save a copy of the path, because the path list itself keeps changing as the search goes on.
123413path12still need4paths saved124done with 4 → remove it from the path
path[1, 2]
remaining4
Leaf 4 has been checked, so pop it. The path is back to 1, 2, exactly as node 2 left it, so its next branch starts clean.
123413path121still need3paths saved124add 1 to the path → still need 3
node1
remaining3
path[1, 2, 1]
Step into node 1: push it onto the path and subtract it, so the path 1, 2, 1 still needs 3. Node 1 has no children, so this is a full root-to-leaf path and can be checked.
123413path121still need3paths saved124leaf but still need 3 → no match
remaining3
The path 1, 2, 1 ends here and adds up to 4, not 7. Nothing is saved, and since a leaf has no children there is nothing else to try below it.
123413path12still need4paths saved124done with 1 → remove it from the path
path[1, 2]
remaining4
Leaf 1 has been checked, so pop it. The path is back to 1, 2, exactly as node 2 left it, so its next branch starts clean.
123413path1still need6paths saved124done with 2 → remove it from the path
path[1]
remaining6
Every branch below node 2 is finished, so pop it. The path is back to 1, exactly as node 1 left it, so its next branch starts clean.
123413path13still need3paths saved124add 3 to the path → still need 3
node3
remaining3
path[1, 3]
Step into node 3: push it onto the path and subtract it, so the path 1, 3 still needs 3. Node 3 has children, so the path is not finished yet; try them left first.
123413path133still need0paths saved124add 3 to the path → still need 0
node3
remaining0
path[1, 3, 3]
Step into node 3: push it onto the path and subtract it, so the path 1, 3, 3 still needs 0. Node 3 has no children, so this is a full root-to-leaf path and can be checked.
123413path133still need0paths saved124133leaf and need 0 → save a copy of the path
remaining0
saved2
A leaf with nothing left to find: 1, 3, 3 adds up to 7. Save a copy of the path, because the path list itself keeps changing as the search goes on.
123413path13still need3paths saved124133done with 3 → remove it from the path
path[1, 3]
remaining3
Leaf 3 has been checked, so pop it. The path is back to 1, 3, exactly as node 3 left it, so its next branch starts clean.
123413path1still need6paths saved124133done with 3 → remove it from the path
path[1]
remaining6
Every branch below node 3 is finished, so pop it. The path is back to 1, exactly as node 1 left it, so its next branch starts clean.
123413pathstill need7paths saved124133done with 1 → remove it from the path
path[]
remaining7
Every branch below node 1 is finished, so pop it. The path is empty again and the search is over.
123413pathstill need7paths saved124133answer: 2 paths
result[1, 2, 4], [1, 3, 3]
Every root-to-leaf path was tried once. The saved copies are the answer, in left-to-right order of their leaves.
05

Common pitfalls

Saving the list instead of a copy

✗ Wrong
res.append(path)
✓ Right
res.append(path[:])

Every saved entry points to the same list, which is popped back to empty by the end. For [1, 2] with target 3 the result becomes [[]] instead of [[1, 2]].

Treating a one-child node as a leaf

✗ Wrong
if (not node.left or not node.right) and remaining == 0:
✓ Right
if not node.left and not node.right and remaining == 0:

For [1, 2] with target 1, the root has only a left child, so or saves [1]. The only root-to-leaf path is 1 → 2, which sums to 3, so the answer is [].

Stopping once the sum passes the target

✗ Wrong
if remaining < 0:
    return
✓ Right
# no early exit: keep going to the leaf

Values can be negative. For [1, 2, null, -3] with target 0, the remaining target is already −1 after the root, so the search stops there, yet 1 + 2 + (−3) is exactly 0 and [[1, 2, -3]] is lost. The early return also skips the pop.

Forgetting to pop

✗ Wrong
dfs(node.left, remaining)
dfs(node.right, remaining)
✓ Right
dfs(node.left, remaining)
dfs(node.right, remaining)
path.pop()

Values from a finished branch stay in the list. For [1, 2, 3] with target 4, the right leaf is reached with the list [1, 2, 3] and saves that instead of [1, 3].

06

Edge cases

Empty tree

root is None, so the search never starts and the result is [].

Single node equal to the target, e.g. [5] with target 5

The root has no children, so it is also a leaf, and [[5]] is returned.

07

Complexity

Time
O(n²)
Space
O(n)
Visiting the nodes is O(n); copying saved paths is the extra cost. A long chain that splits into many leaves, all matching (say every value 0 and target 0), gives about n/4 paths of length n/2 each, so O(n²) values are copied. The recursion and the path list are O(h), which is O(n) on a chain; the output is not counted.
08

Path Sum II FAQ

What is the difference between Path Sum, Path Sum II and Path Sum III?

Path Sum (112) returns true or false: does any root-to-leaf path hit the target? Path Sum II (113) returns every such path. Path Sum III (437) counts downward paths that may start and end at any node, which needs prefix sums instead of a single remaining target.

Can it be done without recursion?

Yes. Push (node, remaining, path) onto a stack (or a queue for BFS), giving each child its own new path list. It avoids deep recursion on a 5,000-node chain, but it copies a path for every node instead of only for matches, so it uses more memory.