用python实现平衡二叉树的增删查改
时间: 2024-11-11 07:13:42 浏览: 12
python实现二叉树,数据结构,包括增删查改等功能
在Python中,可以使用内置的数据结构如`list`或自定义`Node`和`BinaryTree`类来模拟一个简单的平衡二叉搜索树(Balanced Binary Search Tree,BBST),比如AVL树。这里简述如何实现基本操作:
1. **创建节点** (插入):
```python
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.height = 1
class BinaryTree:
def insert(self, root, value):
if not root:
return Node(value)
elif value < root.value:
root.left = self.insert(root.left, value)
else:
root.right = self.insert(root.right, value)
root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
balance = self.getBalance(root)
# 旋转调整
if balance > 1 and value < root.left.value:
return self.rightRotate(root)
elif balance < -1 and value > root.right.value:
return self.leftRotate(root)
elif balance > 1 and value > root.left.value:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
elif balance < -1 and value < root.right.value:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
```
2. **查找** (查询):
```python
def search(self, root, value):
if not root or root.value == value:
return root
elif value < root.value:
return self.search(root.left, value)
else:
return self.search(root.right, value)
```
3. **删除** (删除特定值):
```python
def delete(self, root, value):
if not root:
return root
if value < root.value:
root.left = self.delete(root.left, value)
elif value > root.value:
root.right = self.delete(root.right, value)
else: # 找到需要删除的节点
if root.left is None: # 只有右子树
temp = root.right
root = None
return temp
elif root.right is None: # 只有左子树
temp = root.left
root = None
return temp
# 有两个子节点
temp = self.getMinValueNode(root.right) # 获取右子树最小值节点
root.value = temp.value # 替换为最小值
root.right = self.delete(root.right, temp.value)
if root is None:
return root
root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right))
balance = self.getBalance(root)
# 如果不平衡,则应用适当的旋转
# ...
return root
```
4. **其他辅助函数**:
```python
def getHeight(self, root):
if not root:
return 0
return root.height
def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)
# 左旋
def leftRotate(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
return y
# 右旋
def rightRotate(self, y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right))
x.height = 1 + max(self.getHeight(x.left), self.getHeight(x.right))
return x
def getMinValueNode(self, root):
current = root
while current.left is not None:
current = current.left
return current
```
阅读全文