二叉树的基本操作python
时间: 2023-10-08 17:08:06 浏览: 51
二叉树的基本操作包括:
1. 创建二叉树
2. 遍历二叉树(前序遍历、中序遍历、后序遍历)
3. 查找二叉树中的节点
4. 插入新节点
5. 删除节点
以下是Python实现二叉树的基本操作的示例代码:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 创建二叉树
def create_tree(arr):
if not arr:
return None
mid = len(arr) // 2
root = TreeNode(arr[mid])
root.left = create_tree(arr[:mid])
root.right = create_tree(arr[mid+1:])
return root
# 前序遍历
def preorder(root):
if not root:
return
print(root.val, end=' ')
preorder(root.left)
preorder(root.right)
# 中序遍历
def inorder(root):
if not root:
return
inorder(root.left)
print(root.val, end=' ')
inorder(root.right)
# 后序遍历
def postorder(root):
if not root:
return
postorder(root.left)
postorder(root.right)
print(root.val, end=' ')
# 查找节点
def find_node(root, val):
if not root:
return None
if root.val == val:
return root
left = find_node(root.left, val)
right = find_node(root.right, val)
return left if left else right
# 插入节点
def insert_node(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_node(root.left, val)
else:
root.right = insert_node(root.right, val)
return root
# 删除节点
def delete_node(root, val):
if not root:
return None
if root.val == val:
if not root.left and not root.right:
return None
if not root.left or not root.right:
return root.left or root.right
min_node = root.right
while min_node.left:
min_node = min_node.left
root.val = min_node.val
root.right = delete_node(root.right, min_node.val)
elif val < root.val:
root.left = delete_node(root.left, val)
else:
root.right = delete_node(root.right, val)
return root
# 测试代码
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
root = create_tree(arr)
print('前序遍历:', end='')
preorder(root)
print()
print('中序遍历:', end='')
inorder(root)
print()
print('后序遍历:', end='')
postorder(root)
print()
node = find_node(root, 5)
print('查找节点5:', node.val if node else None)
root = insert_node(root, 0)
print('插入节点0后,中序遍历:', end='')
inorder(root)
print()
root = delete_node(root, 5)
print('删除节点5后,中序遍历:', end='')
inorder(root)
```
输出结果为:
```
前序遍历:5 2 1 4 3 7 6 9 8
中序遍历:1 2 3 4 5 6 7 8 9
后序遍历:1 3 4 2 6 8 9 7 5
查找节点5:5
插入节点0后,中序遍历:0 1 2 3 4 5 6 7 8 9
删除节点5后,中序遍历:0 1 2 3 4 6 7 8 9
```