在python中,标准库未直接提供自平衡二叉查找树(如avl或红黑树)的实现,通常通过第三方库`sortedcontainers`中的`sortedlist`来高效维护动态有序数据,或者使用`heapq`模块处理基于优先级的动态场景。若需严格实现自平衡二叉查找树以支持插入、删除和搜索的平均o(log n)复杂度,建议采用自定义类封装节点逻辑并实现旋转操作,或利用`blist`等扩展序列结构。对于大多数需要动态排序且频繁增删的应用,`sortedlist`是更优的工程选择,它内部使用b树变体保证性能。

如何使用SortedList维护动态有序数据
使用`sortedcontainers.SortedList`可以直接维护一个自动排序的动态列表。该容器支持O(log n)的插入和删除操作,并允许通过索引快速访问元素。初始化时传入初始数据,后续调用`.add()`添加新元素,`.pop()`移除指定索引的元素,列表始终保持有序状态。这适用于需要频繁查询第K大/小值或范围统计的场景。

from sortedcontainers import SortedList
# 初始化空列表或带初始数据的列表
sl = SortedList([10, 5, 20, 15])
print("初始状态:", sl)
# 动态添加元素
sl.add(7)
sl.add(25)
print("添加后:", sl)
# 删除特定索引的元素 (例如删除索引1的元素,即7)
sl.pop(1)
print("删除后:", sl)
# 查找某个值的索引 (二分查找)
index = sl.index(15)
print("15的索引:", index)
预期输出: 初始状态: SortedList([5, 10, 15, 20]) 添加后: SortedList([5, 7, 10, 15, 20, 25]) 删除后: SortedList([5, 10, 15, 20, 25]) 15的索引: 2
如何手动实现简单的AVL树节点结构
若不能使用第三方库,可以手动实现AVL树的节点类。核心在于维护每个节点的`height`属性,并在插入或删除后检查平衡因子(左子树高度减右子树高度)。当平衡因子的绝对值大于1时,执行相应的旋转操作(左旋、右旋或双旋)来恢复平衡。这种实现适合学习算法原理或在不允许外部依赖的环境中使用。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
def get_height(node):
if not node:
return 0
return node.height
def get_balance(node):
if not node:
return 0
return get_height(node.left) - get_height(node.right)
def right_rotate(y):
x = y.left
T2 = x.right
x.right = y
y.left = T2
y.height = 1 + max(get_height(y.left), get_height(y.right))
x.height = 1 + max(get_height(x.left), get_height(x.right))
return x
def left_rotate(x):
y = x.right
T2 = y.left
y.left = x
x.right = T2
x.height = 1 + max(get_height(x.left), get_height(x.right))
y.height = 1 + max(get_height(y.left), get_height(y.right))
return y
def insert(node, key):
if not node:
return AVLNode(key)
if key 1 and key node.right.key:
return left_rotate(node)
# Left Right Case
if balance > 1 and key > node.left.key:
node.left = left_rotate(node.left)
return right_rotate(node)
# Right Left Case
if balance <p>预期输出:前序遍历: 30 20 10 25 40 50 (注:具体遍历顺序取决于旋转细节,但树保持平衡)</p><h2>AVL树插入过程中何时触发右旋操作</h2><p>在手动实现的AVL树中,右旋操作通常在“右右情况”(Right-Right Case)下触发。具体来说,当在一个节点的右子树的右子树上插入了新节点,导致该节点的平衡因子变为-2(即右子树比左子树高2层)时,就需要对该节点进行右旋。右旋会将该节点的右孩子提升为新根,原节点变为新根的左孩子,从而降低右子树的高度,恢复平衡。</p>
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










