leetcode 111. Minimum Depth of Binary Tree

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.

Example:

Given binary tree [3,9,20,null,null,15,7],

   3
  / \
 9  20
   /  \
  15   7

return its minimum depth = 2.

这个题可以用BFS,也可以用DFS,关于具体思路可以见我的博客园的博客(C++版)leetcode111 C++

python代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        minnum = 1
        if not root:
            return 0
        num = []
        num.append(root)
        while len(num):
            length = len(num)
            for i in range(length):
                T = num[0]
                num.pop(0)
                if not T.left and not T.right:
                    return minnum
                if T.left:
                    num.append(T.left)
                if T.right: #不能写成elif!!!
                    num.append(T.right)
            minnum += 1
        return minnum

对了,切记,在if T.right上,不能写成elif T.right。试想,如果一个根有左右子结点,那么,用这个只能添加左子树,而右子树就被忽略了。

你可能感兴趣的:(leetcode 111. Minimum Depth of Binary Tree)