FAANGPrep Sprint
Path Sum II
Find all root-to-leaf paths where each path's sum equals the targetSum.
Examples
Two paths sum to 22.
Problem Understanding
Unlike Path Sum I, we need to return every root-to-leaf path whose values add up to targetSum, not just whether one exists.
Since we need the paths themselves, we keep one path list that always holds the nodes from the root down to the current call. When we reach a leaf that completes the sum, we add a copy of path to result.
Algorithm Strategy (Backtracking)
We use DFS with backtracking.
- State: one shared
pathlist, andremaining, what is still needed. - Action: entering a node, append
node.valtopath. - Check: at a leaf whose value is exactly
remaining, save a copy ofpath. - Recurse: otherwise call the left and right children with
remaining - node.val. - Backtrack: pop
node.valoffpathbefore returning, so the parent’s other branch starts from the right path.
Interactive Visualization
TARGET 22 · OUTLINED = path
CALL dfs(root, target)
Path length
0
Saved
0
path
Empty path
result
No paths saved yet
Call dfs(root, 22) with an empty path
Next
dfs(5, remaining 22)
Tree
target
The outlined nodes are path itself: a node joins when its call starts and leaves just before its call returns. Each visited node shows what was still needed below it, and a leaf whose path is saved turns green.
