python 二叉链表实现树的遍历
时间: 2023-06-12 11:04:13 浏览: 114
python二叉树遍历的实现方法
二叉链表是二叉树的一种链式存储结构,每个节点包含三个域:数据域、左子树指针域和右子树指针域。二叉链表的遍历有三种方式:前序遍历、中序遍历和后序遍历。以下是 Python 代码实现:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinaryTree:
def __init__(self):
self.root = None
def preOrder(self, root):
if root:
print(root.val, end=' ')
self.preOrder(root.left)
self.preOrder(root.right)
def inOrder(self, root):
if root:
self.inOrder(root.left)
print(root.val, end=' ')
self.inOrder(root.right)
def postOrder(self, root):
if root:
self.postOrder(root.left)
self.postOrder(root.right)
print(root.val, end=' ')
```
使用示例:
```python
tree = BinaryTree()
tree.root = TreeNode(1)
tree.root.left = TreeNode(2)
tree.root.right = TreeNode(3)
tree.root.left.left = TreeNode(4)
tree.root.left.right = TreeNode(5)
print("Preorder traversal:")
tree.preOrder(tree.root)
print("\nInorder traversal:")
tree.inOrder(tree.root)
print("\nPostorder traversal:")
tree.postOrder(tree.root)
```
输出结果:
```
Preorder traversal:
1 2 4 5 3
Inorder traversal:
4 2 5 1 3
Postorder traversal:
4 5 2 3 1
```
阅读全文