Minimum Depth of Binary Tree - 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: A leaf is a node with no children.

Input & Output

Example 1 — Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 2
💡 Note: The shortest path is from root 3 to leaf 9, which has depth 2 (3 → 9). The other leaves are at depth 3.
Example 2 — Single Node
$ Input: root = [2]
Output: 1
💡 Note: The root is also a leaf node, so the minimum depth is 1.
Example 3 — Skewed Tree
$ Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
💡 Note: This is a right-skewed tree where the only leaf is at depth 5: 2 → 3 → 4 → 5 → 6.

Constraints

  • The number of nodes in the tree is in the range [0, 105].
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Minimum Depth of Binary Tree BFS Approach INPUT Binary Tree Structure: 3 9 LEAF 20 15 7 Array Representation: [3, 9, 20, null, null, 15, 7] D=1 D=2 D=3 ALGORITHM STEPS 1 Initialize BFS Queue = [(root, depth=1)] 2 Process Level 1 Dequeue node 3 (depth=1) Has children, not leaf 3 Add Children Queue = [(9,2), (20,2)] 4 Process Level 2 Dequeue node 9 (depth=2) LEAF FOUND! Return 2 Queue State at Discovery: 9 20 ... Level-by-level traversal FINAL RESULT Shortest Path Found: 3 9 LEAF NODE Node 1 Node 2 Minimum Depth: 2 OK - Path 3 --> 9 2 nodes in shortest path Key Insight: BFS guarantees finding the minimum depth first because it explores level by level. The first leaf node encountered is always at the minimum depth. DFS would need to explore all paths. Time: O(n), Space: O(n) where n = number of nodes. TutorialsPoint - Minimum Depth of Binary Tree | BFS Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
89.2K Views
Medium Frequency
~15 min Avg. Time
2.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