二叉树的遍历完整代码
时间: 2024-01-06 12:05:30 浏览: 109
以下是二叉树的三种遍历方式的完整代码:
. 前序遍历:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rightdef preOrder(root):
if root is None:
return
print(root.val, end=" ")
preOrder(root.left)
preOrder(root.right)
# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 前序遍历二叉树
preOrder(root)
```
2. 中序遍历:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inOrder(root):
if root is None:
return
inOrder(root.left)
print(root.val, end=" ")
inOrder(root.right)
# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 中序遍历二叉树
inOrder(root)
```
3. 后序遍历:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postOrder(root):
if root is None:
return
postOrder(root.left)
postOrder(root.right)
print(root.val, end=" ")
# 创建二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 后序遍历二叉树
postOrder(root)
```
阅读全文