← All patterns
11 / 29
Trees & Recursion

Tree DFS

📚
Picture this

A scholar plunges down one towering bookshelf to the very floor before ever sidestepping to the next aisle.

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

pathdepthroot-to-leafsubtreediameterancestor

Ask yourself

  1. Need info that bubbles up from children?
  2. Root-to-leaf paths, depth, diameter, LCA?
  3. Recurse left & right, combine results.

Canonical template

function dfs(node: TreeNode | null): number {
  if (!node) return 0;
  const left = dfs(node.left);
  const right = dfs(node.right);
  return 1 + Math.max(left, right);
}

Common pitfalls

Missing the null base case.

Combining child results in the wrong order/way.