Tree Depth-First Search
Recursive tree solutions — path sums, root-to-leaf paths, LCA, diameter and max path sum, using the "return up, update global" recipe.
Tree DFS explores each branch fully before backtracking, usually via recursion. Nearly every tree problem fits one of two shapes:
- Top-down: pass information down (running sum, current path, allowed range) as arguments.
- Bottom-up: compute something for each subtree and return it up (height, sum, "is balanced"), combining at the parent.
- Root-to-leaf paths, path sums, paths matching a sequence.
- Properties of subtrees: height, balance, sizes, sums, whether it's a BST.
- Lowest common ancestor, distances between nodes.
- "Maximum path anywhere in the tree" (diameter, max path sum).
- Tree DP (house robber III, cameras).
Top-down: path sum
boolean hasPathSum(TreeNode n, int target) {
if (n == null) return false;
if (n.left == null && n.right == null) return target == n.val; // leaf
return hasPathSum(n.left, target - n.val) || hasPathSum(n.right, target - n.val);
}
// All root-to-leaf paths with the sum (backtracking on a shared path)
void allPaths(TreeNode n, int remaining, List<Integer> path, List<List<Integer>> res) {
if (n == null) return;
path.add(n.val);
if (n.left == null && n.right == null && remaining == n.val) res.add(new ArrayList<>(path));
allPaths(n.left, remaining - n.val, path, res);
allPaths(n.right, remaining - n.val, path, res);
path.remove(path.size() - 1); // backtrack
}def has_path_sum(n, target):
if not n:
return False
if not n.left and not n.right:
return target == n.val
return has_path_sum(n.left, target - n.val) or has_path_sum(n.right, target - n.val)
def all_paths(root, target):
res, path = [], []
def dfs(n, remaining):
if not n:
return
path.append(n.val)
if not n.left and not n.right and remaining == n.val:
res.append(path[:])
dfs(n.left, remaining - n.val)
dfs(n.right, remaining - n.val)
path.pop() # backtrack
dfs(root, target)
return resfunction hasPathSum(n: TreeNode | null, target: number): boolean {
if (!n) return false;
if (!n.left && !n.right) return target === n.val;
return hasPathSum(n.left, target - n.val) || hasPathSum(n.right, target - n.val);
}Paths that can start anywhere (going downward): prefix sums along the root-to-node path with a hash map — exactly Prefix sum on a tree. O(n).
Bottom-up: return one thing, update a global with another
Maximum path sum (a path may start and end anywhere): at each node, the best path through it uses both children, but the value you return to the parent can only extend one side.
int best = Integer.MIN_VALUE;
int maxPathSum(TreeNode root) { gain(root); return best; }
int gain(TreeNode n) {
if (n == null) return 0;
int l = Math.max(0, gain(n.left)); // drop negative branches
int r = Math.max(0, gain(n.right));
best = Math.max(best, n.val + l + r); // path bending at n (global answer)
return n.val + Math.max(l, r); // path continuing up to the parent
}def max_path_sum(root):
best = float("-inf")
def gain(n):
nonlocal best
if not n:
return 0
l, r = max(0, gain(n.left)), max(0, gain(n.right))
best = max(best, n.val + l + r) # path through n
return n.val + max(l, r) # path extendable upward
gain(root)
return bestfunction maxPathSum(root: TreeNode | null): number {
let best = -Infinity;
const gain = (n: TreeNode | null): number => {
if (!n) return 0;
const l = Math.max(0, gain(n.left)), r = Math.max(0, gain(n.right));
best = Math.max(best, n.val + l + r);
return n.val + Math.max(l, r);
};
gain(root);
return best;
}The same recipe solves diameter (return depth, update with left + right), longest univalue path, and binary tree cameras.
Lowest common ancestor
TreeNode lca(TreeNode n, TreeNode p, TreeNode q) {
if (n == null || n == p || n == q) return n;
TreeNode l = lca(n.left, p, q), r = lca(n.right, p, q);
if (l != null && r != null) return n; // p and q on different sides
return l != null ? l : r;
}def lca(n, p, q):
if not n or n is p or n is q:
return n
l, r = lca(n.left, p, q), lca(n.right, p, q)
if l and r:
return n
return l or rfunction lca(n: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
if (!n || n === p || n === q) return n;
const l = lca(n.left, p, q), r = lca(n.right, p, q);
return l && r ? n : l ?? r;
}Tree DP: house robber III
Return two values per node: best loot if this node is robbed, and best if it isn't. rob = n.val + notRob(left) + notRob(right); notRob = max(left) + max(right). O(n), no memo table needed.
- Maximum Depth of Binary Treeeasy
- Same Tree / Symmetric Treeeasy
- Path Sumeasy
- Diameter of Binary Treereturn depth, update globaleasy
- Balanced Binary Treereturn −1 when unbalancedeasy
- Path Sum IIbacktrackingmedium
- Path Sum IIIprefix sums on the pathmedium
- Validate Binary Search Treepass (lo, hi) downmedium
- Lowest Common Ancestor of a Binary Treemedium
- Construct Binary Tree from Preorder and Inordermedium
- House Robber IIIreturn a pairmedium
- Binary Tree Maximum Path Sumhard
- Binary Tree Cameras3-state tree DPhard
- Top-down: pass state down as parameters; bottom-up: return subtree results.
- "Return one thing, update a global with another" solves diameter and max path sum.
- Backtrack (pop) when collecting paths in a shared list.
- Tree DP returns multiple values per node (e.g. rob / not rob).
- O(n) time, O(h) space.