洛谷b3642+二叉树的遍历
时间: 2024-01-21 17:14:59 浏览: 159
洛谷b3642是一个关于二叉树遍历的问题,下面是二叉树的遍历方法的介绍和示例代码:
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)
print(preorderTraversal(root)) # 输出:[1, 2, 4, 5, 3]
```
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)
print(inorderTraversal(root)) # 输出:[4, 2, 5, 1, 3]
```
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)
print(postorderTraversal(root)) # 输出:[4, 5, 2, 3, 1]
```
阅读全文