Skip to main content

14. Minimum Depth of Binary Tree

easyAsked at Tesla

Find the minimum number of nodes on a path from root to leaf.

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

Problem

Given the root of a binary tree, return its minimum depth — the shortest path from root to any leaf in terms of node count.

Constraints

  • 0 <= node count <= 10^5
  • -1000 <= node.val <= 1000

Examples

Example 1

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

Example 2

Input
root = [2,null,3,null,4,null,5,null,6]
Output
5

Approaches

1. Naive recursion

Min over both children — careful with the single-child edge case.

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

Tradeoff:

2. BFS level order

Return depth on first leaf encountered.

Time
O(n)
Space
O(w)
function minDepthBFS(root) {
  if (!root) return 0;
  const q = [[root, 1]];
  while (q.length) {
    const [n, d] = q.shift();
    if (!n.left && !n.right) return d;
    if (n.left) q.push([n.left, d+1]);
    if (n.right) q.push([n.right, d+1]);
  }
}

Tradeoff:

Tesla-specific tips

Tesla prefers BFS for shortest-path-style problems — same shape as the breadth-first frontier used in real-time graph planning where you want the first viable trajectory, not the deepest.

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 Minimum Depth of Binary Tree and other Tesla interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →