Python实现二叉树的7种遍历方法详解
本文详细总结了Python中二叉树的7种常见遍历方式,涵盖前序、中序、后序及层次遍历。针对每种遍历方法,分别提供了递归和迭代两种实现思路,并附带完整的Python代码示例。文章旨在帮助开发者深入理解二叉树结构及其遍历逻辑,适用于数据结构学习与算法面试准备。
Python二叉树遍历概述
本文通过具体实例,系统讲解在Python环境下实现二叉树常见遍历操作的方法,供读者参考学习。
二叉树定义与节点结构
首先明确二叉树的基本定义:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
前序遍历:递归与迭代实现
接下来介绍二叉树的前序遍历方法。
第一种实现方式采用递归策略。
def preorder(root,res=[]):
if not root:
return
res.append(root.val)
preorder(root.left,res)
preorder(root.right,res)
return res
第二种实现方式采用迭代策略。
def preorder(root):
res=[]
if not root:
return []
stack=[root]
while stack:
node=stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node,left)
return res
中序遍历:递归与迭代实现
随后介绍二叉树的中序遍历方法。
中序遍历的第一种实现方式采用递归策略。
def inorder(root,res=[]):
if not root:
return
inorder(root.left,res)
res.append(root.val)
inorder(root.right,res)
return res
中序遍历的第二种实现方式采用迭代策略。
def inorder(root):
stack=[]
node=root
res=[]
while stack or node:
while node:
stack.append(node)
node=node.left
node=stack.pop()
res.append(node.val)
node=node.right
return res
后序遍历:递归与迭代实现
接着介绍二叉树的后序遍历方法。
后序遍历的第一种实现方式采用递归策略。
def laorder(root,res=[]):
if not root:
return
laorder(root.left,res)
laorder(root.right,res)
res.append(root.val)
return res
后序遍历的第二种实现方式采用迭代策略。
def laorder(root):
stack=[root]
res=[]
while stack:
node=stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res.append(node.val)
return res[::-1]
层次遍历:迭代实现
最后介绍二叉树的层次遍历方法。
层次遍历采用迭代策略实现。
def levelorder(root):
queue=[root]
res=[]
while queue:
node=queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(node.val)
return res
若读者对Python其他技术细节感兴趣,可进一步查阅本站相关专题,包括《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》以及《Python入门与进阶经典教程》。
希望上述内容能对读者的Python程序设计工作提供实际帮助。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









