📅  最后修改于: 2023-12-03 15:13:33.915000             🧑  作者: Mango
AVL树是一种自平衡二叉搜索树,每个节点的左右子树高度差的绝对值不超过1,以此保证树的平衡。在AVL树中进行插入、删除、查找操作的时间复杂度都是O(logn)。
AVL树的插入操作需要维护平衡,大致过程如下:
旋转操作分为四种情况,分别是LL旋转、LR旋转、RR旋转和RL旋转。具体实现细节可以参考代码。
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.height = 0
class AVLTree:
def __init__(self):
self.root = None
def getHeight(self, node):
if node is None:
return -1
else:
return node.height
def getBalance(self, node):
if node is None:
return 0
else:
return self.getHeight(node.left) - self.getHeight(node.right)
def insert(self, val):
self.root = self.insertNode(self.root, val)
def insertNode(self, node, val):
if node is None:
return Node(val)
elif val < node.val:
node.left = self.insertNode(node.left, val)
else:
node.right = self.insertNode(node.right, val)
node.height = 1 + max(self.getHeight(node.left), self.getHeight(node.right))
balance = self.getBalance(node)
# LL旋转
if balance > 1 and val < node.left.val:
return self.rightRotate(node)
# RR旋转
if balance < -1 and val > node.right.val:
return self.leftRotate(node)
# LR旋转
if balance > 1 and val > node.left.val:
node.left = self.leftRotate(node.left)
return self.rightRotate(node)
# RL旋转
if balance < -1 and val < node.right.val:
node.right = self.rightRotate(node.right)
return self.leftRotate(node)
return node
def leftRotate(self, node):
newRoot = node.right
node.right = newRoot.left
newRoot.left = node
node.height = 1 + max(self.getHeight(node.left), self.getHeight(node.right))
newRoot.height = 1 + max(self.getHeight(newRoot.left), self.getHeight(newRoot.right))
return newRoot
def rightRotate(self, node):
newRoot = node.left
node.left = newRoot.right
newRoot.right = node
node.height = 1 + max(self.getHeight(node.left), self.getHeight(node.right))
newRoot.height = 1 + max(self.getHeight(newRoot.left), self.getHeight(newRoot.right))
return newRoot
AVL树是一种自平衡二叉搜索树,插入操作需要维护平衡,通过旋转操作来重新平衡。AVL树的时间复杂度为O(logn),适用于需要频繁插入、删除、查找的场景。