14. Minimum Depth of Binary Tree
easyAsked at SpotifyFind the minimum number of nodes along the shortest path from root to a leaf.
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.
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 DFS
Recurse both subtrees; carefully handle single-child nodes
- Time
- O(n)
- Space
- O(h)
function minDepth(r){if(!r)return 0;if(!r.left)return 1+minDepth(r.right);if(!r.right)return 1+minDepth(r.left);return 1+Math.min(minDepth(r.left),minDepth(r.right));}Tradeoff:
2. BFS level order
First leaf encountered in BFS gives the answer. Stops immediately, perfect for unbalanced trees.
- Time
- O(n)
- Space
- O(w)
function minDepth(root) {
if (!root) return 0;
const q = [[root, 1]];
while (q.length) {
const [node, d] = q.shift();
if (!node.left && !node.right) return d;
if (node.left) q.push([node.left, d + 1]);
if (node.right) q.push([node.right, d + 1]);
}
}Tradeoff:
Spotify-specific tips
Spotify likes early-exit BFS here because their shortest-path traversals on artist-similarity graphs lean on the same idea — terminate as soon as you reach the goal layer.
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 Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →