14. Minimum Depth of Binary Tree
easyAsked at InstacartFind the minimum depth (shortest root-to-leaf path) — Instacart uses BFS preference here to test whether you understand early termination.
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 node down to the nearest leaf node.
Constraints
The number of nodes in the tree is in the range [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. DFS recursion
Recurse left and right; combine carefully when one side is null.
- 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 with early exit
Stop at the first leaf encountered by level-order traversal.
- 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:
Instacart-specific tips
Instacart's interviewers love BFS here — they explicitly ask why DFS wastes work on extremely deep delivery-region trees.
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 Instacart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →