网站程序 制作国际新闻最新消息十条
引言
DFS
深度优先算法:从一个节点开始,一直搜索,直到一个叶子节点或者无法搜索下去。
BFS
广度优先算法(层序遍历):从一个节点开始,逐层搜索节点。
实现
DFS(深度优先)
class Solution:def connect(self, root: 'Node') -> 'Node':pre = []def dfs(node: 'Node', depth: int) -> None:if node is None:returnif depth == len(pre): pre.append(node)else: pre[depth].next = node pre[depth] = nodedfs(node.left, depth + 1)dfs(node.right, depth + 1)dfs(root, 0) return root
这个主要是通过一直遍历左边子树的左节点,核心思想是pre[depth].next = node pre[depth] = node,这个就直接使用将左子树的左节点作为下一个值,直到后面没有值了,这里面的一个判断if depth == len(pre)就做一个是否当前深度等于列表长度。然后就是递归左右子树,进入下一层。
BFS(广度优先/层序遍历)
class Solution:def connect(self, root: 'Node') -> 'Node':if root is None:return Noneq = [root]while q:for x, y in pairwise(q):x.next = ytmp = qq = []for node in tmp:if node.left: q.append(node.left)if node.right: q.append(node.right)return root
广度优先搜索和深度优先搜索的主要区别就是广度优先遍历是没有一直往左子树的左节点的,而是直接用pairwise将两个值进行分组,并将下一节点放在分组的另一个值上,for x,y in pairwose(q):
x.next = y,然后将所有的值添加到队列中。对了,队列是一种很适合用于层序遍历的,因为队列是先进先出,而且队列由列表表示。