14. Minimum Depth of Binary Tree
easyAsked at GlassdoorFind the shortest path from root to any leaf — Glassdoor uses this to grade whether you correctly handle one-sided trees (often missed).
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 the root to the nearest leaf. A leaf is a node with no children.
Constraints
The number of nodes is in [0, 10^5]-1000 <= Node.val <= 1000
Examples
Example 1
root = [3,9,20,null,null,15,7]2Example 2
root = [2,null,3,null,4,null,5,null,6]5Approaches
1. Naive DFS
1 + min(minDepth(left), minDepth(right)) — but be careful with null children.
- Time
- O(n)
- Space
- O(h)
function minDepth(root) {
if (!root) return 0;
if (!root.left) return 1 + minDepth(root.right);
if (!root.right) return 1 + minDepth(root.left);
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}Tradeoff:
2. BFS short-circuit
First leaf encountered in level-order traversal 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:
Glassdoor-specific tips
Glassdoor specifically watches for the one-sided null trap; mentioning BFS early-exit shows you optimize for the kind of skewed comment-tree they actually see in production.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Minimum Depth of Binary Tree and other Glassdoor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →