The Path Sum II problem asks you to find all root-to-leaf paths in a binary tree where the sum of node values equals a target. Return all such paths. This coding problem uses DFS with backtracking to collect all valid paths. The DFS, backtracking, binary tree, and tree interview pattern is the core.
Microsoft, Meta, Amazon, TikTok, Google, Bloomberg, and DoorDash ask this because it extends Path Sum I from a boolean check to collecting all valid paths. It tests backtracking on trees — maintaining a current path, adding to results at valid leaves, and restoring state on backtrack.
DFS backtracking. Maintain current_path list. At each node: append node.val to current_path, subtract from remaining. If at a leaf and remaining=0: add a copy of current_path to results. Recurse on left and right children. Backtrack: remove node.val from current_path.
Tree: 5→(4→(11→(7,2)),8→(13,4→(5,1))). target=22. Valid paths: 5→4→11→2 (sum=22), 5→8→4→5? (=22). Result: [[5,4,11,2],[5,8,4,5]].
Tree backtracking is a critical skill. The pattern: push, recurse, pop (backtrack). Always add a copy of the current path to results — not the path itself. Practice this pattern on all "find all paths" tree problems. The key insight: backtracking on trees is implicit in recursion — the call stack maintains the path, and explicit pop/append manages the shared data structure.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Smallest String Starting From Leaf | Medium | Solve | |
| Path Sum III | Medium | Solve | |
| Binary Tree Longest Consecutive Sequence | Medium | Solve | |
| Sum Root to Leaf Numbers | Medium | Solve | |
| Binary Tree Paths | Easy | Solve |