Path Sum II (LeetCode 113): Solution and Explanation

Medium
Backtracking
Tree
Depth First Search
Binary Tree

Given the root of a binary tree and a target number, collect every path that runs from the root down to a leaf and whose node values add up to the target. Each path is returned as a list of the values along it.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The first version of this problem only asked whether a matching path exists. Now you need the paths themselves, so you cannot just carry a number down the tree. You also need to remember which nodes you passed through to get where you are.

The naive way to do that is to create a brand new list for every recursive call, something like path + [node.val]. It is correct, but it allocates a fresh list at every node, even on the many branches that never lead to an answer.

Backtracking fixes this by sharing one list for the whole search. When the DFS steps onto a node it appends that value, explores both children, and then pops the value before returning to the parent. At any moment the list holds exactly the path from the root to the current node, which is the classic choose, explore, unchoose pattern.

Alongside the list you pass the remaining target, reduced by each value you pass. At a leaf whose value equals the remaining target, the shared list is a complete answer, so you store a copy of it. The copy matters, because the shared list will keep changing as the search continues.

Approach: DFS backtracking with a shared path

  1. Create an empty result list res and define a helper dfs(root, remaining, path).
  2. If the node is None, return immediately, since there is nothing to explore.
  3. Append the node's value to path, so the list now describes the route from the root to this node.
  4. If the node is a leaf and remaining == root.val, append list(path), a copy of the current path, to res.
  5. Recurse into the left and right children with remaining - root.val.
  6. After both calls return, pop the last value off path to undo the choice before going back to the parent.
  7. Start the search with dfs(root, targetSum, []) and return res.

Step-by-step example

root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
  1. Visit 5 with remaining 22, then 4 with remaining 17, then 11 with remaining 13. The path is now [5,4,11].
  2. Visit leaf 7 with remaining 2. Since 2 is not 7, nothing is recorded, and 7 is popped off the path.
  3. Visit leaf 2 with remaining 2. The values match, so a copy of [5,4,11,2] is added to the result, then 2 is popped.
  4. Back up through 11 and 4, popping each, then visit 8 with remaining 17. Its left child 13 is a leaf with remaining 9, which does not match.
  5. Visit 4 under 8 with remaining 9, then its left leaf 5 with remaining 5. The values match, so [5,8,4,5] is recorded.
  6. The final leaf 1 sees remaining 5 and does not match, so the result is [[5,4,11,2],[5,8,4,5]].

Code: Python, Java, C++

1class Solution:
2    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
3        res = []
4        
5        def dfs(root, remaining, path):
6            if not root:
7                return
8            
9            path.append(root.val)
10            
11            if not root.left and not root.right and remaining == root.val:
12                res.append(list(path))
13            
14            dfs(root.left, remaining - root.val, path)
15            dfs(root.right, remaining - root.val, path)
16            
17            path.pop()
18            
19        dfs(root, targetSum, [])
20        return res

Time and space complexity

Time

O(n²)

The traversal itself visits each node once. Copying a matching path costs up to O(h), and in the worst case many leaves match, so the total is O(n × h), which is O(n²) for a degenerate tree.

Space

O(h)

The recursion stack and the shared path both grow to the height h of the tree. The output list is not counted, though it can itself hold O(n × h) values.

Other approaches

Copy the path at every call (time O(n²), space O(n²))

Pass path + [root.val] into each recursive call instead of appending and popping. The code is shorter and has no undo step, but it allocates a new list at every node, so even a search that finds nothing costs O(n × h) time and memory.

Iterative DFS with parent pointers (time O(n²), space O(n))

Run an explicit stack of (node, running sum) pairs and record each node's parent in a dictionary. When a matching leaf is found, rebuild its path by following parents back to the root and reversing. This avoids recursion limits at the cost of an extra map.

Common mistakes

  • Appending path itself rather than a copy. Every stored entry would point to the same list, which ends up empty once the search finishes.
  • Forgetting the path.pop() after the recursive calls, so values from finished branches leak into later paths.
  • Returning right after recording a match without popping. If you add an early return at a leaf, you must still undo the append first.
  • Stopping a branch because the sum already exceeds the target. Values can be negative, so you must keep going until a leaf.

Frequently asked questions

Why do we append list(path) instead of path?

The search reuses one list and keeps appending and popping. If you store a reference to it, every saved answer changes as the search moves on. list(path) freezes a snapshot of the path at the moment it matched.

What is the time complexity of Path Sum II?

The traversal is O(n), but each matching path is copied in O(h). In the worst case that gives O(n × h), which becomes O(n²) for a skewed tree and about O(n log n) for a balanced one.

How is Path Sum II different from Path Sum?

Path Sum only returns whether one matching path exists, so it can stop early and only carry a number. Path Sum II must find every match and return the actual values, so it has to explore the whole tree and track the current path.