Browse curriculum

FAANGPrep Sprint

Path Sum II

Find all root-to-leaf paths where each path's sum equals the targetSum.

Examples

Input:root = [5,4,8,11,null,13,4,7,2,5,1], targetSum = 22
Output:[[5,4,11,2],[5,8,4,5]]
Explain:

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.

  1. State: one shared path list, and remaining, what is still needed.
  2. Action: entering a node, append node.val to path.
  3. Check: at a leaf whose value is exactly remaining, save a copy of path.
  4. Recurse: otherwise call the left and right children with remaining - node.val.
  5. Backtrack: pop node.val off path before 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

22

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.