二叉树的先序中序后序递归遍历
时间: 2025-01-03 15:38:10 浏览: 45
### 二叉树的先序、中序和后序递归遍历
#### 先序遍历 (Pre-order Traversal)
在先序遍历中,访问顺序为:根节点 -> 左子树 -> 右子树。具体过程如下:
1. 访问当前节点并记录其值。
2. 对左子树执行先序遍历。
3. 对右子树执行先序遍历。
```python
def pre_order_traversal(root):
if root is None:
return []
result = []
# Visit the current node and add its value to results.
result.append(root.val)
# Recursively traverse the left subtree.
result += pre_order_traversal(root.left)
# Recursively traverse the right subtree.
result += pre_order_traversal(root.right)
return result
```
[^1]
#### 中序遍历 (In-order Traversal)
对于中序遍历而言,遵循的是:左子树 -> 根节点 -> 右子树 的原则来进行访问。具体步骤如下所示:
1. 执行对左子树的中序遍历。
2. 当前节点被访问并将它的值加入到结果集中。
3. 接着再做一次针对右侧分支同样的动作——即对其实施中序遍历。
```python
def in_order_traversal(root):
if root is None:
return []
result = []
# Traverse the left subtree recursively.
result += in_order_traversal(root.left)
# Visit this node after traversing all nodes on the left side.
result.append(root.val)
# Finally, visit the right subtree.
result += in_order_traversal(root.right)
return result
```
[^2]
#### 后序遍历 (Post-order Traversal)
最后来看下后序遍历的方式,在这里我们按照这样的路径去走:左子树 -> 右子树 -> 根节点 。也就是说要等到左右两个方向都走过之后才会回到最开始的那个位置来做标记工作。
1. 开始时会先进入左侧部分进行探索直到不能再深入为止;
2. 转向右边继续重复上述行为直至结束;
3. 完成以上两步后再回头处理最初的起点处的数据项。
```python
def post_order_traversal(root):
if root is None:
return []
result = []
# First go as deep into the tree from the left as possible.
result += post_order_traversal(root.left)
# Then do the same thing but starting with the right child of each parent instead.
result += post_order_traversal(root.right)
# After exploring both children fully, finally process the current node itself.
result.append(root.val)
return result
```
[^3]
阅读全文
相关推荐







