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!
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
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
โ Linear Growth
Space Complexity
O(w)
Queue stores at most w nodes, where w is maximum width of tree
โ 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)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code