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.

Intermediate 2 min readLesson 12 of 25

Tree DFS explores each branch fully before backtracking, usually via recursion. Nearly every tree problem fits one of two shapes:

  1. Top-down: pass information down (running sum, current path, allowed range) as arguments.
  2. Bottom-up: compute something for each subtree and return it up (height, sum, "is balanced"), combining at the parent.
72114131485
Path sum 22: 5 → 4 → 11 → 2.
When to use this pattern
  • 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
}

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
}

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;
}

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.

Practice problems
  • 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
Key takeaways
  • 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.