SDE & MLE Prep

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