AVL树的伪代码python
时间: 2023-11-21 20:58:08 浏览: 107
AVL树是一种自平衡二叉搜索树,它的平衡是通过旋转操作来实现的。下面是AVL树的伪代码Python实现:
```python
# AVL树节点定义
class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
# AVL树定义
class AVLTree:
def __init__(self):
self.root = None
# 获取节点高度
def get_height(self, node):
if not node:
return 0
return node.height
# 获取节点平衡因子
def get_balance(self, node):
if not node:
return 0
return self.get_height(node.left) - self.get_height(node.right)
# 右旋操作
def right_rotate(self, y):
x = y.left
t2 = x.right
x.right = y
y.left = t2
y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
x.height = 1 + max(self.get_height(x.left), self.get_height(x.right))
return x
# 左旋操作
def left_rotate(self, x):
y = x.right
t2 = y.left
y.left = x
x.right = t2
x.height = 1 + max(self.get_height(x.left), self.get_height(x.right))
y.height = 1 + max(self.get_height(y.left), self.get_height(y.right))
return y
# 插入操作
def insert(self, root, key):
if not root:
return AVLNode(key)
elif key < root.key:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
root.height = 1 + max(self.get_height(root.left), self.get_height(root.right))
balance = self.get_balance(root)
# 左旋操作
if balance > 1 and key < root.left.key:
return self.right_rotate(root)
# 右旋操作
if balance < -1 and key > root.right.key:
return self.left_rotate(root)
# 左右旋操作
if balance > 1 and key > root.left.key:
root.left = self.left_rotate(root.left)
return self.right_rotate(root)
# 右左旋操作
if balance < -1 and key < root.right.key:
root.right = self.right_rotate(root.right)
return self.left_rotate(root)
return root
```
阅读全文