Minimum Depth of Binary Tree - Problem
Given a binary tree, find its minimum depth - the shortest path from root to any leaf node. Think of it as finding the shallowest leaf in the tree!

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Remember: a leaf is a node with no children (both left and right are null).

Key insight: Unlike maximum depth where we always go deep, here we stop as soon as we find the first leaf node. This makes BFS (level-order traversal) particularly elegant for this problem!

Example: In a tree with root having only a left child, which has two children, the minimum depth is 3 (not 2), because we must reach a true leaf.

Input & Output

example_1.py โ€” Basic Binary Tree
$ Input: root = [3,9,20,null,null,15,7]
โ€บ Output: 2
๐Ÿ’ก Note: The minimum depth is 2, following the path: root โ†’ 9 (which is a leaf). Even though there are deeper nodes (15, 7), we only care about the shortest path to ANY leaf.
example_2.py โ€” Skewed Tree
$ Input: root = [2,null,3,null,4,null,5,null,6]
โ€บ Output: 5
๐Ÿ’ก Note: This is a right-skewed tree where each node only has a right child. The only leaf is node 6, so we must traverse the entire path: 2โ†’3โ†’4โ†’5โ†’6, giving us depth 5.
example_3.py โ€” Single Node
$ Input: root = [1]
โ€บ Output: 1
๐Ÿ’ก Note: A single node is both the root and a leaf. The minimum depth is 1.

Visualization

Tap to expand
Peak (Root)Valley 1 (Leaf)Valley 2 (Deeper)Valley 3 (Deeper)BFS Trail Search:โœ“ Distance 1: Check immediate pathsโœ“ Distance 2: Found Valley 1 - STOP!โœ— Distance 3+: No need to exploreKey Insight:BFS explores by distance,so first valley found isguaranteed to be closest!
Understanding the Visualization
1
Start at Peak
Begin at the mountain peak (root node)
2
Explore Distance 1
Check all locations 1 step away from peak
3
Explore Distance 2
Check all locations 2 steps away - find first valley!
4
Stop Early
No need to explore further distances
Key Takeaway
๐ŸŽฏ Key Insight: BFS naturally finds the shortest path first because it explores nodes level by level. The moment we find any leaf node, we know it's at the minimum depth - no need to explore deeper levels!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

In worst case, might visit all nodes, but often much better

n
2n
โœ“ Linear Growth
Space Complexity
O(w)

Queue stores at most w nodes, where w is maximum width of tree

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [0, 105]
  • -1000 โ‰ค Node.val โ‰ค 1000
  • Tree can be empty (null root)
Asked in
Google 42 Amazon 38 Microsoft 31 Meta 24
52.0K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen