14. Minimum Depth of Binary Tree
easyAsked at TripAdvisorFind the minimum depth of a binary tree from root to nearest leaf.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note that a leaf is a node with no children.
Constraints
0 <= nodes <= 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. Recursive min
1 + min of subtrees, but careful about single-child nodes.
- 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 first leaf
BFS level by level; return depth as soon as the first leaf is dequeued.
- Time
- O(n)
- Space
- O(w)
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:
TripAdvisor-specific tips
TripAdvisor uses min-depth questions to test if you exit search early when finding the closest reviewer in a moderation tree.
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 TripAdvisor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →