Skip to main content

12. Maximum Depth of Binary Tree

easyAsked at DigitalOcean

Find the maximum depth of a binary tree using DFS — a classic recursion warm-up that DigitalOcean uses to assess comfort with tree traversal.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Constraints

  • Number of nodes in range [0, 10^4]
  • -100 <= Node.val <= 100

Examples

Example 1

Input
root = [3,9,20,null,null,15,7]
Output
3

Example 2

Input
root = [1,null,2]
Output
2

Approaches

1. Brute force (iterative BFS)

Level-order traversal counting levels.

Time
O(n)
Space
O(n)
function maxDepth(root) {
  if (!root) return 0;
  const queue = [root];
  let depth = 0;
  while (queue.length) {
    depth++;
    const size = queue.length;
    for (let i = 0; i < size; i++) {
      const node = queue.shift();
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return depth;
}

Tradeoff:

2. Recursive DFS

Return 1 + max of left/right subtree depths; base case is null node returns 0. Clean and minimal with O(h) stack space.

Time
O(n)
Space
O(h)
function maxDepth(root) {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Tradeoff:

DigitalOcean-specific tips

DigitalOcean focuses on cloud networking and distributed systems, so interviewers tie tree depth problems to resource hierarchy depth in infrastructure graphs — mention that insight.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Maximum Depth of Binary Tree and other DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →