本文用python3实现二叉树的广度优先遍历(BFS)和深度优先遍历(DFS)。
完整代码链接:https://github.com/toanoyx/BasicAlgorithm/tree/master/tree
广度优先遍历
广度遍历又叫层次遍历。用队列实现,依次将根,左子树,右子树存入队列,按照队列的先进先出规则来实现层次遍历。
# 层次遍历(广度优先)
def BFS(root):
if root:
res = []
queue = [root]
while queue:
currentNode = queue.pop(0)
res.append(currentNode.val)
if currentNode.left:
queue.append(currentNode.left)
if currentNode.right:
queue.append(currentNode.right)
return res
深度优先遍历
用栈实现,先将根入栈,再将根出栈,并将根的右子树,左子树存入栈,按照栈的先进后出规则来实现深度优先遍历。
# 深度优先
def DFS(root):
if root:
res = []
stack = [root