使用python实现二叉树的三种遍历
时间: 2024-10-20 09:03:14 浏览: 34
在Python中,二叉树的遍历主要有三种基本方式:前序遍历、中序遍历和后序遍历。
1. **前序遍历**(Preorder Traversal):首先访问根节点,然后递归地遍历左子树,最后遍历右子树。对于每个节点,它的操作顺序是`根 -> 左 -> 右`。Python代码示例如下:
```python
def preorder_traversal(root):
if root is not None:
print(root.val) # 访问根节点
preorder_traversal(root.left) # 遍历左子树
preorder_traversal(root.right) # 遍历右子树
```
2. **中序遍历**(Inorder Traversal):先遍历左子树,然后访问根节点,最后遍历右子树。对于每个节点,操作顺序是`左 -> 根 -> 右`。代码如下:
```python
def inorder_traversal(root):
if root is not None:
inorder_traversal(root.left)
print(root.val) # 访问根节点
inorder_traversal(root.right)
```
3. **后序遍历**(Postorder Traversal):先遍历左子树和右子树,最后访问根节点。对于每个节点,其操作顺序是`左 -> 右 -> 根`。Python实现如下:
```python
def postorder_traversal(root):
if root is not None:
postorder_traversal(root.left)
postorder_traversal(root.right)
print(root.val) # 访问根节点
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)