队列特性:
时间复杂度:
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
网友评论