Skip to main content

14. Minimum Depth of Binary Tree

easyAsked at Unity

Find the shortest root-to-leaf path. Unity uses this in BVH descent to find the nearest collision candidate.

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

Problem

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

Constraints

  • 0 <= 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 all paths

Recurse to every leaf, track min depth.

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

Tradeoff:

2. BFS first leaf

Walk levels with a queue; first leaf seen is the answer.

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

Unity-specific tips

Unity prefers the BFS variant because nearest-hit BVH descent must stop at the first viable leaf to stay inside the frame budget.

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

Practice these live with InterviewChamp.AI →