ESC

Type to search the knowledge base.

Maximum Depth of Binary Tree

Height of a binary tree via DFS recursion or BFS levels — the tree warm-up every interviewer trusts.

beginner3 min read
  • dsa
  • tree
  • interview
  • Google
  • Meta
  • Amazon

The problem

Given the root of a binary tree, return its maximum depth — number of nodes along the longest root-to-leaf path.

    3
   / \
  9  20
    /  \
   15   7
→ depth 3

Empty tree → 0.

Node shape

class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

Brute / iterative level scan

BFS by levels; depth = number of levels.

function maxDepthBfs(root: TreeNode | null): number {
  if (!root) return 0;
  const q: TreeNode[] = [root];
  let depth = 0;
  while (q.length) {
    const size = q.length;
    for (let i = 0; i < size; i++) {
      const node = q.shift()!;
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
    depth++;
  }
  return depth;
}

Optimal (and simplest): DFS

function maxDepth(root: TreeNode | null): number {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
Time O(n) — visit every node
Space O(h) recursion; O(n) BFS queue worst case

Both are fine in interviews. DFS is shorter; BFS avoids deep recursion on skewed trees.

Edge cases

  • null root → 0
  • Single node → 1
  • Left-skewed / right-skewed chain
  • Unbalanced trees — max of sides, not sum

Common bugs

  • Returning Math.max(left, right) without + 1
  • Counting edges instead of nodes (clarify with interviewer; LC uses nodes)
  • shift() without freezing level size in BFS

Interview delivery

  1. Define depth (nodes on longest path).
  2. Base case null → 0.
  3. One-liner DFS or BFS levels.
  4. O(n) time.
  5. Mention skewed-tree stack depth if probed.

Definition check

Some textbooks define height as edges on the longest path (root alone height 0). LeetCode maximum depth counts nodes. Confirm in one sentence: “I’ll return 0 for null and 1 for a leaf.”

DFS vs BFS when to prefer

DFS recursion BFS levels
Code length shortest more boilerplate
Skewed tree O(n) stack risk O(1) width on chain
Balanced O(log n) stack O(n) queue at bottom

Default DFS; switch if they mention stack limits or want level-order practice.

  • Minimum depth (careful: leaf definition).
  • Balanced binary tree (height diff ≤ 1).
  • Diameter (longest path between any nodes — not always through root).

Maximum depth is the building block for all three.

Further reading