#111
Minimum Depth of Binary Tree
EasyTreeDepth-First SearchBreadth-First SearchBinary TreeTree TraversalBreadth-First Search
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a breadth-first search (BFS) to explore the tree level by level. The first time we encounter a leaf node, we can return its depth as the minimum depth.
⚙️
Algorithm
4 steps- 1Step 1: If the tree is empty, return 0.
- 2Step 2: Initialize a queue and add the root node along with its depth (1).
- 3Step 3: While the queue is not empty, dequeue a node and check if it's a leaf. If it is, return its depth.
- 4Step 4: If not a leaf, enqueue its children with incremented depth.
solution.py14 lines
1from collections import deque
2
3def minDepth(root):
4 if not root:
5 return 0
6 queue = deque([(root, 1)])
7 while queue:
8 node, depth = queue.popleft()
9 if not node.left and not node.right:
10 return depth
11 if node.left:
12 queue.append((node.left, depth + 1))
13 if node.right:
14 queue.append((node.right, depth + 1))ℹ
Complexity note: The complexity is O(n) because we may need to visit every node in the tree. The space complexity is O(n) due to the queue storing nodes at each level.
- 1The minimum depth is defined by the first leaf node encountered.
- 2BFS is effective for level-order traversal, making it suitable for this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.