0111. Minimum Depth

Easy | Tree + Level-order Traversal | 444 ms (99.47%), 49 MB (94.42%)

Source: LeetCode - Minimumm Depth of Binary Tree GitHub: Solution / Performance

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.

Extension question of Level-order traversal.

While traversing the tree in level order, we need to record the current level (depth). Then, when we meet the leaf node, we return the current depth directly.

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        # (base case)
        if not root: return 0
        if not root.left and not root.right: return 1
        
        # ==================================================
        #  Binary Tree + Level Order Traversal             =
        # ==================================================
        # time  : O(n)
        # space : O(n), O(log(n)) for average case

        minDepth = 0
        stack = [root]
        
        while stack:
            # loop through stack for current length, pop the first node
            for i in range(len(stack)):
                node = stack.pop(0)
                
                if not node.left and not node.right: return minDepth + 1
                
                if node.left: stack.append(node.left)
                if node.right: stack.append(node.right)
                    
            minDepth += 1
            
        return minDepth

Last updated