美文网首页
python实现leetcode之111. 二叉树的最小深度

python实现leetcode之111. 二叉树的最小深度

作者: 深圳都这么冷 | 来源:发表于2021-09-29 00:11 被阅读0次

解题思路

广度优先遍历
在节点没有孩子节点的时候就是末梢,这时深度最小的叶子结点,直接返回

111. 二叉树的最小深度

代码

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

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        queue = [(root, 1)]
        while queue:
            node, depth = queue.pop(0)
            if not node.left and not node.right:
                return depth
            else:
                if node.left:
                    queue.append((node.left, depth+1))
                if node.right:
                    queue.append((node.right, depth+1))
效果图

相关文章

网友评论

      本文标题:python实现leetcode之111. 二叉树的最小深度

      本文链接:https://www.haomeiwen.com/subject/adufnltx.html