二叉树的前中后序遍历,层序遍历,BFS,DFS的递归和非递归实现(Python)
前言
二叉树中DFS分为前中后序遍历,DFS如果在图中,就没有前中后序遍历说法,如果在矩阵中,变化顺序就由上下左右随机组合了
二叉树中BFS和层序遍历又有些区别
二叉树定义
class TreeNode:
def __init__(self, x, L=None, R=None):
self.val = x
self.left = L
self.right = R
遍历的递归实现
深度遍历的运行过程是先进后出的,自然的方法是栈和递归
广度遍历的运行过程是先进先出的,自然的方法是队列
前序
class Solution(object):
def dfs(self,root):
"""
根->左->右
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
print(root.val)
dfs(root.left)
dfs(root.right)
中序
class Solution(object):
def dfs(self,root):
"""
根->左->右
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
dfs(root.left)
print(root.val)
dfs(root.right)
后序
class Solution(object):
def dfs(self,root):
"""
根->左->右
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return
dfs(root.left)
dfs(root.right)
print(root.val)
遍历的非递归实现
前序
class Solution(object):
def preorderTraversal(self,root):
"""
根->左->右
:type root: TreeNode
:rtype: List[int]
"""
stack = [root]
res = []
while stack:
cur = stack.pop()
res.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return res
中序
class Solution(object):
def inorderTraversal(self, root):
"""
左->根->右
:type root: TreeNode
:rtype: List[int]
"""
stack = []
cur = root
res = []
while stack or cur:
if cur:
stack.append(cur)
cur = cur.left
else:
node = stack.pop()
res.append(node.val)
cur = node.right
return res
后序
class Solution(object):
def postorderTraversal(self, root):
"""
左->右->根
:type root: TreeNode
:rtype: List[int]
"""
stack1 = [root]
stack2 = []
while stack1:
cur = stack1.pop()
stack2.append(cur.val)
if cur.left:
stack1.append(cur.left)
if cur.right:
stack1.append(cur.right)
return stack2[::-1]
BFS
def bfs(root):
queue = []
# 根节点加入队列中
queue.append(root)
res = []
while queue:
temp = queue.pop(0)
l = temp.left
r = temp.right
if l:
queue.append(l)
if r:
queue.append(r)
res.append(temp.val)
return res
层序
层序遍历要求的输入结果和 BFS 是不同的。层序遍历要求我们区分每一层,也就是返回一个二维数组。而 BFS 的遍历结果是一个一维数组,无法区分每一层。
def bfs(root):
queue = []
# 根节点加入队列中
queue.append(root)
outlist = []
while queue:
res = []
i = 0
temp = queue.pop(0)
numberFlag=len(queue) #这一步记录当前层中节点的个数
while i <numberFlag: #这里再遍历每一层
point=queue.pop(0)
res.append(point.val)
if point.left:
queue.append(point.left)
if point.right:
queue.append(point.right)
i+=1
outList.append(res)
return outList
引用
[0] 二叉树的前中后序遍历的非递归实现(Python)
var code = “152bff39-4019-48dc-b0f0-5c5c0e46ba86”