Skip to main content

14. Minimum Depth of Binary Tree

easyAsked at Slack

Find the depth of the nearest leaf in a binary tree.

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

Problem

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

Constraints

  • Nodes count in [0, 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

DFS every root-to-leaf path, track minimum.

Time
O(n)
Space
O(h)
let best = Infinity;
function dfs(n,d){ if(!n) return; if(!n.left&&!n.right) best=Math.min(best,d); dfs(n.left,d+1); dfs(n.right,d+1);}
dfs(root,1);
return root? best : 0;

Tradeoff:

2. BFS

Level-order traversal returns the depth of the first leaf encountered, which is the minimum.

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:

Slack-specific tips

Slack interviewers prefer BFS for min-depth because it short-circuits — DFS forces you to explore every leaf, which they'll call out.

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

Practice these live with InterviewChamp.AI →