← PatternsTree Patterns → Tree Path Problems🛤 Path Problems
🛤
Tree Path Problems — Root-to-Leaf & Any-Node Paths
Two complementary patterns: backtracking DFS tracks the current path from root to leaf, adding/removing nodes as you descend and backtrack. Max-gain DFS uses bottom-up return values to evaluate paths passing through any node — the global answer is updated at each step while the return value propagates only the best single branch upward.
Path Sum / Path Sum II — backtrack DFS, carry remaining sum down
Sum Root to Leaf Numbers — multiply accumulated value × 10 + digit
Count paths with target sum — prefix sum + hashmap (Path Sum III)
Max path sum (any node) — post-order gain, discard negatives
Good nodes count — carry max-so-far down the path
💡 Key distinction: root-to-leaf paths use explicit path.add / path.remove (backtracking). Any-node paths never store the path — they compute a gain value bottom-up and update a global ans via L + R + node.val.
⚡ Complexity
Time
O(n)
Space (stack)
O(h)
Where n = number of nodes, h = tree height.
Balanced tree: O(log n) stack depth.
Skewed tree: O(n) stack depth.
Path Sum II also uses O(h) for the current path list — worst case O(n) if all nodes form the path.
Every node visited exactly once: O(n) time.
Live Animation · Tree Path Problems · LC #113
Problem
Given a binary tree [root=5, left=4→11→(7,2), right=8→(13, 4→5)] and targetSum = 22, find all root-to-leaf paths whose node values sum to the target. Backtracking DFS: carry remaining sum down, add to path list, undo on return.
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,5], targetSum = 22 · Answer: [[5,4,11,2],[5,8,4,5]]
🛤 Path Sum II backtracking — tree has target=22. We descend, building a path list. At each leaf we check if remaining sum == 0. We backtrack by removing the last element.
// dfs(node, rem=22, path=[]) — path sum backtracking
🌲 Tree (target = 22)
on path
found!
dead end
default
🌲 Tree (Max Path Sum)
computing
best path
gain computed
default
🛤 Current Path
[ empty ]
rem22/ target 22
✅ Found Paths
— none yet —
📈 Max Path Gain
— computing... —
ans-∞
return:—
📝 Result:
[ waiting... ]
🧩 Pattern Skeleton
Java 8
// ─── Root-to-Leaf Paths (Path Sum II) ────────────────List<List<Integer>> result = newArrayList<>();
voiddfs(TreeNode n, int rem, List<Integer> path) {
if (n == null) return;
path.add(n.val); // add to pathif (n.left == null && n.right == null && rem == n.val)
result.add(newArrayList<>(path)); // found pathdfs(n.left, rem - n.val, path);
dfs(n.right, rem - n.val, path);
path.remove(path.size() - 1); // backtrack
}
// ─── Max Path Sum (any node to any node) ─────────────int ans = Integer.MIN_VALUE;
intmaxGain(TreeNode n) {
if (n == null) return0;
int L = Math.max(0, maxGain(n.left)); // discard negativesint R = Math.max(0, maxGain(n.right));
ans = Math.max(ans, L + R + n.val); // path through nreturnMath.max(L, R) + n.val; // contribute upward
}