美文网首页
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)

    二叉树的bfs:

  • 2019-05

    5.6 symmetric-tree (easy)看一个树是否镜面对称,第一直觉是bfs,但还是用的递归和stac...

  • 走迷宫(BFS例题)

    BFS例题---走迷宫 BFS对应数据结构queue BFS算法时间复杂度O(n^2) BFS算法不走走过的点 的...

  • 什么时候用BFS,什么时候用DFS

    参考什么时候用dfs,什么时候用bfs 参考什么时候用DFS,什么时候用BFS? BFS的缺点适用情况 BFS的一...

  • Binary Tree(2)

    BFS vs DFS for Binary Tree What are BFS and DFS for Binar...

  • BFS/DFS python模板与实现

    BFS BFS在搜索完第k层的节点之前,是不会搜索第k+1层的节点的。 BFS原理 BFS所用的是队列。把每个还没...

  • Chapter12—搜索—广搜

    1. 题目列表 POJ3126(BFS) POJ3087(BFS) POJ3414(BFS+路径打印) 2. 广搜...

  • BFS及其应用

    内容概要: BFS类的实现 BFS求解连通分量 BFS求解无向图点对之间的一条最短路径 BFS判定无环图和二分图 ...

  • 8.19 - hard - 64

    317 . Shortest Distance from All Buildings 典型的BFS的题目,BFS可...

  • H - 8 HDU - 1495

    BFS

网友评论

      本文标题:bfs (easy)

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