Path Sum II
Master this topic with zero to advance depth.
Path Sum II
All root-to-leaf paths summing to target.
Level I: DFS with List Copying
Intuition
To find all root-to-leaf paths that sum to a target, we can use Depth First Search (DFS). In this basic version, each time we recurse, we create a new copy of the current path. This is simpler to implement but less space-efficient than backtracking.
Thought Process
- At each node, subtract
node.valfrom the remaining target. - If it's a leaf node and
remainingTarget == 0, add the current path to the result list. - Recurse to left and right children with a fresh copy of the current path.
Detailed Dry Run
| Tree | Target | Path | Remaining | Action |
|---|---|---|---|---|
| 5 | 22 | [5] | 17 | Recurse |
| 4 | 17 | [5, 4] | 13 | Recurse |
| 11 | 13 | [5, 4, 11] | 2 | Recurse (to 2) |
| 2 | 2 | [5, 4, 11, 2] | 0 | SUCCESS! |
Level II: Iterative BFS (Queue with State)
Intuition
We can use a Queue of Triplets (node, currentPath, currentSum) to simulate BFS. For each node, we push its children along with the updated path and sum. This avoids recursion entirely while still exploring the tree level by level.
Thought Process
- Store state as
[node, path_list, rem_sum]. - When reaching a leaf, if
rem_sum == node.val, save path. - Push children with
path + [node.val]andrem_sum - node.val.
Detailed Dry Run
Queue: [(5, [], 22)]. Pop 5, Push (4, [5], 17) and (8, [5], 17). Pop 4, Push (11, [5, 4], 13)...
Level III: Optimal (Backtracking)
Intuition
Thought Process
Instead of copying the array at every step, we use a single global list and perform backtracking. We add the current node to the list, recurse, and then remove the current node (the last element) before returning from the function call.
Patterns
DFS + Backtracking: Keep state clean for previous caller by undoing changes.
Complexity
- Time: (Every node visited once)
- Space: (For the recursive stack and the single path list)
Detailed Dry Run
| Action | Path | Sum (Remaining) |
|---|---|---|
| Visit 5 | [5] | 17 |
| Visit 4 | [5, 4] | 13 |
| Visit 11 | [5, 4, 11] | 2 |
| Pop 11 | [5, 4] | 13 |
⚠️ Common Pitfalls & Tips
You still need to copy the list when adding it to the result (res.add(new ArrayList<>(path))), otherwise all paths in the result will end up empty at the end of the process!
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.