AVL树左旋和右旋操作详解及 Python 代码示例
AVL树是一种自平衡二叉搜索树,它的平衡条件是任何节点的左右子树高度差不超过1。当插入或删除节点后破坏了平衡条件时,需要进行旋转操作来重新平衡。
左旋和右旋是AVL树中的两种基本旋转操作。左旋是将一个节点的右子树提升为根节点,而右子树的左子树成为原来节点的右子树。右旋则是将一个节点的左子树提升为根节点,而左子树的右子树成为原来节点的左子树。
下面是一些示例代码,演示了如何对AVL树进行左旋和右旋操作:
# AVL树节点类
class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
# 左旋操作
def left_rotate(node):
new_root = node.right
node.right = new_root.left
new_root.left = node
node.height = max(get_height(node.left), get_height(node.right)) + 1
new_root.height = max(get_height(new_root.left), get_height(new_root.right)) + 1
return new_root
# 右旋操作
def right_rotate(node):
new_root = node.left
node.left = new_root.right
new_root.right = node
node.height = max(get_height(node.left), get_height(node.right)) + 1
new_root.height = max(get_height(new_root.left), get_height(new_root.right)) + 1
return new_root
# 获取节点高度
def get_height(node):
if node is None:
return 0
return node.height
在实现AVL树时,需要注意以下几点:
-
旋转操作会改变节点的高度,因此在旋转后需要更新节点的高度信息。
-
左旋和右旋的实现很相似,只是方向相反。因此可以考虑将左旋和右旋实现为一个通用的旋转函数,并通过参数控制旋转方向。
-
在插入或删除节点时,需要递归地更新每个节点的高度并检查平衡条件是否被破坏。如果平衡条件被破坏,则需要进行相应的旋转操作来重新平衡。
原文地址: https://www.cveoy.top/t/topic/njwB 著作权归作者所有。请勿转载和采集!