Depth-First Search
Medium
Path Sum II
Find all root-to-leaf paths where each path's sum equals the targetSum.
10 min read
Solve on LeetCodeExamples
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 all distinct paths that satisfy the condition, not just a boolean.
Since we need to store the actual path (list of nodes), we'll need to maintain a current_path list as we traverse. When we hit a valid leaf, we add a copy of current_path to our global result.
Algorithm Strategy (Backtracking)
We use DFS with Backtracking.
- State: Maintain
current_pathlist andremaining_sum. - Action: On visiting node, add
node.valtocurrent_path. - Check: If leaf &
node.val == remaining_sum, save a copy of the path. - Recurse: Call left and right children.
- Backtrack: Crucially, pop the last element (
node.val) fromcurrent_pathbefore returning to parent. This cleans up the state for other branches.
Interactive Visualization
Step 1 / 21
5
curr
4
8
11
13
4
7
2
5
1
5
04
18
211
34
13
54
67
72
85
91
10Visit 5. Path: [5]. Remaining needed: 17.
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy (Backtracking)
- Interactive Visualization
- Dry Run: Target = 22
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
