b3642 二叉树的遍历python
时间: 2023-09-21 07:10:19 浏览: 91
遍历二叉树程序
二叉树的遍历有三种常用方法:前序遍历、中序遍历和后序遍历。下面是使用Python实现这三种遍历方法的示例代码:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 前序遍历
def preorderTraversal(root):
if not root:
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 not root:
return []
result = []
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.val)
node = node.right
return result
# 后序遍历
def postorderTraversal(root):
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result[::-1]
```
你可以根据需要调用这些函数来遍历二叉树。比如,假设有以下二叉树:
```
1
/ \
2 3
/ \ / \
4 5 6 7
```
可以使用以下代码进行遍历:
```python
# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
# 前序遍历
print("前序遍历:", preorderTraversal(root)) # 输出: [1, 2, 4, 5, 3, 6, 7]
# 中序遍历
print("中序遍历:", inorderTraversal(root)) # 输出: [4, 2, 5, 1, 6, 3, 7]
# 后序遍历
print("后序遍历:", postorderTraversal(root)) # 输出: [4, 5, 2, 6, 7, 3, 1]
```
希望这个示例能帮助到你!
阅读全文