14. Minimum Depth of Binary Tree
easyAsked at OlaFind the shortest path from the root to any leaf in a binary tree.
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. A leaf is a node with no children.
Constraints
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. DFS full traversal
Recurse all paths and track min.
- Time
- O(n)
- Space
- O(h)
const go = n => {
if (!n) return Infinity;
if (!n.left && !n.right) return 1;
return 1 + Math.min(go(n.left), go(n.right));
};
return root ? go(root) : 0;Tradeoff:
2. BFS shortest path
Level-order; return depth on the first leaf encountered. Exits early on shallow leaves.
- Time
- O(n)
- Space
- O(n)
function minDepth(root) {
if (!root) return 0;
let 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:
Ola-specific tips
Ola interviewers ask why BFS beats DFS here when most leaves sit at the top of the tree; tie it to early-stopping on shallow shortest-supply matches.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →