二叉树前序中序后序遍历?
时间: 2024-02-04 16:09:35 浏览: 111
以下是Python实现二叉树前序、中序和后序遍历的示例代码:
1. 前序遍历(Preorder Traversal):根节点 -> 左子树 -> 右子树
```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 root is None:
return []
result = []
result.append(root.val)
result += preorderTraversal(root.left)
result += preorderTraversal(root.right)
return result
# 示例用法
# 构建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 前序遍历
preorder = preorderTraversal(root)
print("前序遍历结果:", preorder)
```
2. 中序遍历(Inorder Traversal):左子树 -> 根节点 -> 右子树
```python
def inorderTraversal(root):
if root is None:
return []
result = []
result += inorderTraversal(root.left)
result.append(root.val)
result += inorderTraversal(root.right)
return result
# 示例用法
# 构建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 中序遍历
inorder = inorderTraversal(root)
print("中序遍历结果:", inorder)
```
3. 后序遍历(Postorder Traversal):左子树 -> 右子树 -> 根节点
```python
def postorderTraversal(root):
if root is None:
return []
result = []
result += postorderTraversal(root.left)
result += postorderTraversal(root.right)
result.append(root.val)
return result
# 示例用法
# 构建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 后序遍历
postorder = postorderTraversal(root)
print("后序遍历结果:", postorder)
```
阅读全文