Skip to main content

14. Minimum Depth of Binary Tree

easyAsked at Box

Find the minimum depth path to a leaf — Box uses this when computing the shortest path through a permission-inheritance tree.

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

Problem

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Constraints

  • 0 <= number of nodes <= 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. DFS

Recurse and take min height, careful when one side is null.

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

Tradeoff:

2. BFS short-circuit

Level-order traversal returns at first leaf — early-exits without exploring deep branches.

Time
O(n)
Space
O(n)
function minDepth(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:

Box-specific tips

Box prefers BFS short-circuit — they grade for not over-exploring deep branches when answering shortest-permission-path queries.

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 Box interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →