经典的bfs

题目:二叉树的最小深度

leetcode:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not  root: return 0
        q = []
        visted = ()
        depth = 1

        q.append(root)
        
        while q:
            size = q.__len__()
            for s in range(size):
                node = TreeNode()
                node = q.pop(0)
                
                if not node.left and not node.right:
                    return depth
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            depth += 1
        return depth

 

posted @ 2022-02-23 23:22  pie神  阅读(26)  评论(0)    收藏  举报