美文网首页
bfs (easy)

bfs (easy)

作者: warManHy | 来源:发表于2021-01-02 22:05 被阅读0次
    队列特性:
    时间复杂度:
    bfs: 图的广度优先遍历
    
    from collections import deque
    def bfs(graph, root):
        queue = [root]
        seen = set([root])
        while len(queue):
            head = queue[0]
            # head = queue.popleft() 
            for i in graph[head]:
                if i not in seen:
                    queue.append(i)
                    seen.add(i)
    

    二叉树的bfs:

    # 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 levelOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            if not root:
                return []
            ans = []
            queue = [root]
            while queue:
                tmp = []
                l = len(queue)
                for i in range(l):
                    node = queue.pop(0)
                    tmp.append(node.val)
                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)
                ans.append(tmp)
            return ans
    
    

    相关文章

      网友评论

          本文标题:bfs (easy)

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