Home
DSA Patterns
Depth-First Search
Path Sum II
Path Sum II (LeetCode 113)
Path Sum II (LeetCode 113): 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.
Dry Run: [1, 2, 3], Target = 4
Tree: [1, 2, 3], target = 4
| Step | Call | path | Action |
|---|---|---|---|
| 1 | dfs(1, 4) | [1] |
Not a leaf: go left needing 3 |
| 2 | dfs(2, 3) | [1, 2] |
A leaf, but 3 ≠ 2: call both empty children |
| 3 | back in dfs(2) | [1] |
Pop 2 |
| 4 | dfs(3, 3) | [1, 3] |
A leaf and 3 = 3: save [1, 3] |
| 5 | back in dfs(3) | [1] |
Pop 3 |
| 6 | back in dfs(1) | [] |
Pop 1: return [[1, 3]] |
Edge Cases & Common Mistakes
- Save a copy:
pathis one shared list. Adding it toresultdirectly would leave every entry pointing at the same list, which ends up empty. Addlist(path),new ArrayList<>(path)or[...path]. - Pop in every case: the pop must run after both branches (and also after a saved leaf) or the path keeps nodes that are no longer being visited.
- Negative values: the sum can pass the target and come back, so never stop early just because the running sum is too large.
Solution
Backtracking approach.
Path Sum II Code
1var pathSum = function(root, targetSum) {2 const result = [];3 const path = [];45 function dfs(node, remaining) {6 if (!node) return;7 path.push(node.val);8 if (!node.left && !node.right && remaining === node.val) {9 result.push([...path]);10 } else {11 dfs(node.left, remaining - node.val);12 dfs(node.right, remaining - node.val);13 }14 path.pop();15 }1617 dfs(root, targetSum);18 return result;19};
Path Sum II in Python, Java, C++, TypeScript and C
Path Sum II in Python
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
result = []
path = []
def dfs(node, remaining):
if not node:
return
path.append(node.val)
if not node.left and not node.right and remaining == node.val:
result.append(list(path))
else:
dfs(node.left, remaining - node.val)
dfs(node.right, remaining - node.val)
path.pop()
dfs(root, targetSum)
return resultPath Sum II in Java
class Solution {
private final List<List<Integer>> result = new ArrayList<>();
private final List<Integer> path = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
dfs(root, targetSum);
return result;
}
private void dfs(TreeNode node, int remaining) {
if (node == null) return;
path.add(node.val);
if (node.left == null && node.right == null && remaining == node.val) {
result.add(new ArrayList<>(path));
} else {
dfs(node.left, remaining - node.val);
dfs(node.right, remaining - node.val);
}
path.remove(path.size() - 1);
}
}Path Sum II in C++
class Solution {
vector<vector<int>> result;
vector<int> path;
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
dfs(root, targetSum);
return result;
}
void dfs(TreeNode* node, int remaining) {
if (!node) return;
path.push_back(node->val);
if (!node->left && !node->right && remaining == node->val) {
result.push_back(path);
} else {
dfs(node->left, remaining - node->val);
dfs(node->right, remaining - node->val);
}
path.pop_back();
}
};Path Sum II in TypeScript
function pathSum(root: TreeNode | null, targetSum: number): number[][] {
const result: number[][] = [];
const path: number[] = [];
function dfs(node: TreeNode | null, remaining: number): void {
if (!node) return;
path.push(node.val);
if (!node.left && !node.right && remaining === node.val) {
result.push([...path]);
} else {
dfs(node.left, remaining - node.val);
dfs(node.right, remaining - node.val);
}
path.pop();
}
dfs(root, targetSum);
return result;
}Path Sum II in C
static void dfs(struct TreeNode* node, int remaining, int* path, int* depth, int** result, int* sizes, int* count) {
if (node == NULL) return;
path[(*depth)++] = node->val;
if (node->left == NULL && node->right == NULL && remaining == node->val) {
result[*count] = malloc(*depth * sizeof(int));
memcpy(result[*count], path, *depth * sizeof(int));
sizes[(*count)++] = *depth;
} else {
dfs(node->left, remaining - node->val, path, depth, result, sizes, count);
dfs(node->right, remaining - node->val, path, depth, result, sizes, count);
}
(*depth)--;
}
int** pathSum(struct TreeNode* root, int targetSum, int* returnSize, int** returnColumnSizes) {
int** result = malloc(5000 * sizeof(int*));
*returnColumnSizes = malloc(5000 * sizeof(int));
int path[5000];
int depth = 0;
*returnSize = 0;
dfs(root, targetSum, path, &depth, result, *returnColumnSizes, returnSize);
return result;
}More practice: DSA interview questions with answers · patterns cheat sheet
