111. Minimum Depth of Binary Tree
Problem
Return the minimum depth of a binary tree: the number of nodes on the shortest path from the root to a leaf (a node with no children).
Example: [3,9,20,null,null,15,7] → 2; [2,null,3,null,4,null,5,null,6] → 5
BFS level by level; the first leaf reached gives the minimum depth (DFS must be careful: a node with one child isn't a leaf).
Complexity: O(n).
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
q, depth = deque([root]), 1
while q:
for _ in range(len(q)):
n = q.popleft()
if not n.left and not n.right:
return depth
q.extend(c for c in (n.left, n.right) if c)
depth += 1
assert Solution().minDepth(make_tree([3, 9, 20, None, None, 15, 7])) == 2
assert Solution().minDepth(make_tree([2, None, 3, None, 4, None, 5, None, 6])) == 5
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null) return 1 + minDepth(root.right);
if (root.right == null) return 1 + minDepth(root.left);
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
q, depth := []*TreeNode{root}, 1
for { // BFS: the first leaf found is the shallowest
next := []*TreeNode{}
for _, n := range q {
if n.Left == nil && n.Right == nil {
return depth
}
if n.Left != nil {
next = append(next, n.Left)
}
if n.Right != nil {
next = append(next, n.Right)
}
}
q, depth = next, depth+1
}
}