二叉树结构的定义:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
对于以上二叉树,其四种遍历顺序分别是:
中序(左中右):7-2-1-8-4-3-5
前序(中左右):1-2-7-8-3-4-5
后序(左右中):7-8-2-4-5-3-1
层序(逐层自左向右):1-2-3-7-8-4-5
递归法
对于前中后序遍历,使用递归法最容易实现,只需要调用函数的顺序即可。
前序
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def travelsal(root):
if root == None:
return
res.append(root.val) # 中
travelsal(root.left) # 左
travelsal(root.right) # 右
travelsal(root)
return res
中序
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def travelsal(root):
if root == None:
return
travelsal(root.left) # 左
res.append(root.val) # 中
travelsal(root.right) # 右
travelsal(root)
return res
后序
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def travelsal(root):
if root == None:
return
travelsal(root.left) # 左
travelsal(root.right) # 右
res.append(root.val) # 中
travelsal(root)
return res
迭代法
层序遍历(基于队列实现)
通过队列的先进先出来实现按层输出
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
queue = [root]
if not root:
return res
while queue:
path = []
for i in range(len(queue)): # 对该层进行遍历
cur = queue.pop(0)
path.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
res.append(path) # 遍历完一层加到res
return res
中序遍历(基于栈)
左中右,要注意原则 左链入栈
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
path = []
st = []
cur = root
while cur: # 先走到左链的最下面
st.append(cur)
cur = cur.left
while st:
node = st.pop()
path.append(node.val)
p = node.right
while p: # 只对左链入栈
st.append(p)
p = p.left
return path
前序遍历(基于栈)
中左右,当前节点先入path,在右节点入栈,左节点入栈
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
stack = [root]
if not root:
return 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:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
stack = [root]
if not root:
return res
while stack:
cur = stack.pop()
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
res.append(cur.val)
return res[::-1]