Path Sum II Visualizer & Step-by-Step Algorithm Solution

Find all unique root-to-leaf paths where the sum of the node values equals targetSum using DFS backtracking.

Category: trees | Difficulty: Medium

Tags: DFS, Binary Tree, Recursion, Backtracking, All Paths

Path Sum II

5
4
11
7
2
8
13
4
5
1
100%
state
targetSum22
currentPath[]
allPaths[]
remaining22
Initialization
1/36
Explanation

Start pathSum (find all paths) with targetSum = 22.

Source Code
1function pathSum(root, targetSum) {
2 const paths = [];
3 function dfs(node, remaining, path) {
4 if (!node) return;
5 path.push(node.val);
6 if (!node.left && !node.right && remaining === node.val) {
7 paths.push([...path]);
8 }
9 dfs(node.left, remaining - node.val, path);
10 dfs(node.right, remaining - node.val, path);
11 path.pop(); // Backtrack
12 }
13 dfs(root, targetSum, []);
14 return paths;
15}