python二叉树遍历
时间: 2023-10-15 22:31:12 浏览: 98
二叉树的三种遍历方式包括前序遍历、中序遍历和后序遍历。下面是Python实现这三种遍历方式的示例代码:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
# 前序遍历
def preorderTraversal(root):
if root is None:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
# 中序遍历
def inorderTraversal(root):
if root is None:
return []
result = []
stack = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.val)
node = node.right
return result
# 后序遍历
def postorderTraversal(root):
if root is None:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
result.append(node.val)
return result[::-1]
```
使用示例:
```python
# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 前序遍历
print("前序遍历:", preorderTraversal(root)) # 输出: [1, 2, 4, 5, 3]
# 中序遍历
print("中序遍历:", inorderTraversal(root)) # 输出: [4, 2, 5, 1, 3]
# 后序遍历
print("后序遍历:", postorderTraversal(root)) # 输出: [4, 5, 2, 3, 1]
```
以上代码实现了二叉树的前序遍历、中序遍历和后序遍历。希望能对你有所帮助!
阅读全文