Leetcode Tag Search | Back

111. Minimum Depth of Binary Tree

Category: /leetcode

Leetcode Link | BFS template

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.

Solution:

  • BFS level traverse is generally faster than DFS
  • but use more space O(N), leaf level is up to N/2
  • DFS space is O(logn) for the tree depth
def minDepth(self, root: TreeNode) -> int:
    if not root: return 0 
    que = collections.deque()
    que.append(root)
    depth = 1  # root init depth
    while que:
        # go through current level
        for _ in range(len(que)): # use len, not que.
            cur = que.popleft()
            if not cur.left and not cur.right:
                # find a leaf
                return depth
            if cur.left:
                # print(f"add val={cur.left.val}, {depth}")
                que.append(cur.left)
            if cur.right:
                # print(f"add val={cur.right.val}, {depth}")
                que.append(cur.right)
        depth += 1
    return depth

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)