"""Offline Python algorithm lab for Data Structures Chapter 11 (dsa-advanced-tree)."""
import json
VERSION = "Windows x64 CPython 3.12.14 offline DSA lab"
class AVLNode:
def __init__(self, key):
self.key = key
self.height = 1
self.left = None
self.right = None
def avl_h(n):
return n.height if n else 0
def avl_bf(n):
return (avl_h(n.left) - avl_h(n.right)) if n else 0
def right_rotate(y):
x = y.left
t3 = x.right
x.right = y
y.left = t3
y.height = 1 + max(avl_h(y.left), avl_h(y.right))
x.height = 1 + max(avl_h(x.left), avl_h(x.right))
return x
def left_rotate(x):
y = x.right
t2 = y.left
y.left = x
x.right = t2
x.height = 1 + max(avl_h(x.left), avl_h(x.right))
y.height = 1 + max(avl_h(y.left), avl_h(y.right))
return y
def avl_insert(node, key, stats=None):
if not node:
return AVLNode(key)
if key < node.key:
node.left = avl_insert(node.left, key, stats)
elif key > node.key:
node.right = avl_insert(node.right, key, stats)
else:
return node
node.height = 1 + max(avl_h(node.left), avl_h(node.right))
bf = avl_bf(node)
if bf > 1 and key < node.left.key:
if stats is not None:
stats.append("LL")
return right_rotate(node)
if bf < -1 and key > node.right.key:
if stats is not None:
stats.append("RR")
return left_rotate(node)
if bf > 1 and key > node.left.key:
if stats is not None:
stats.append("LR")
node.left = left_rotate(node.left)
return right_rotate(node)
if bf < -1 and key < node.right.key:
if stats is not None:
stats.append("RL")
node.right = right_rotate(node.right)
return left_rotate(node)
return node
def avl_inorder(node, out):
if not node:
return
avl_inorder(node.left, out)
out.append(node.key)
avl_inorder(node.right, out)
def avl_all_balanced(node):
if not node:
return True
if abs(avl_bf(node)) > 1:
return False
return avl_all_balanced(node.left) and avl_all_balanced(node.right)
def case_bst_degeneration_vs_avl_balance():
# 有序插入 1..15:普通 BST 高度退化为 15,AVL 树自动平衡高度为 4
class BSTNode:
def __init__(self, k):
self.key = k
self.left = self.right = None
bst_root = None
for k in range(1, 16):
if bst_root is None:
bst_root = BSTNode(k)
else:
cur = bst_root
while True:
if k < cur.key:
if cur.left is None:
cur.left = BSTNode(k)
break
cur = cur.left
else:
if cur.right is None:
cur.right = BSTNode(k)
break
cur = cur.right
def bst_height(n):
return 0 if not n else 1 + max(bst_height(n.left), bst_height(n.right))
avl_root = None
for k in range(1, 16):
avl_root = avl_insert(avl_root, k)
ino = []
avl_inorder(avl_root, ino)
expected = {
"bst_skewed_height": 15,
"avl_balanced_height": 4,
"avl_strictly_balanced": True,
"avl_inorder_1_to_15": list(range(1, 16)),
}
actual = {
"bst_skewed_height": bst_height(bst_root),
"avl_balanced_height": avl_h(avl_root),
"avl_strictly_balanced": avl_all_balanced(avl_root),
"avl_inorder_1_to_15": ino,
}
return {
"name": "bst_degeneration_vs_avl_balance",
"summary": "有序插入 1..15 对比普通 BST 链表退化(高度 15)与 AVL 树自平衡(高度 4)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_avl_four_rotations_explicit():
scenarios = {
"LL": [30, 20, 10],
"RR": [10, 20, 30],
"LR": [30, 10, 20],
"RL": [10, 30, 20],
}
observed = {}
for label, seq in scenarios.items():
root, stats = None, []
for k in seq:
root = avl_insert(root, k, stats)
ino = []
avl_inorder(root, ino)
observed[label] = {
"rotation": stats,
"root": root.key,
"height": avl_h(root),
"sorted": ino,
}
expected = {
"LL": {"rotation": ["LL"], "root": 20, "height": 2, "sorted": [10, 20, 30]},
"RR": {"rotation": ["RR"], "root": 20, "height": 2, "sorted": [10, 20, 30]},
"LR": {"rotation": ["LR"], "root": 20, "height": 2, "sorted": [10, 20, 30]},
"RL": {"rotation": ["RL"], "root": 20, "height": 2, "sorted": [10, 20, 30]},
}
return {
"name": "avl_four_rotations_explicit",
"summary": "分别触发并校验 AVL 树 LL、RR、LR、RL 四种旋转恢复平衡与中序有序性",
"expected": expected,
"actual": observed,
"passed": observed == expected,
}
def case_red_black_tree_five_invariants():
RED, BLACK = "RED", "BLACK"
class RBNode:
def __init__(self, key, color=RED, left=None, right=None, parent=None):
self.key = key
self.color = color
self.left = left
self.right = right
self.parent = parent
class RBTree:
def __init__(self):
self.NIL = RBNode(None, BLACK)
self.root = self.NIL
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left is not self.NIL:
y.left.parent = x
y.parent = x.parent
if x.parent is self.NIL:
self.root = y
elif x is x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def right_rotate(self, y):
x = y.left
y.left = x.right
if x.right is not self.NIL:
x.right.parent = y
x.parent = y.parent
if y.parent is self.NIL:
self.root = x
elif y is y.parent.right:
y.parent.right = x
else:
y.parent.left = x
x.right = y
y.parent = x
def insert(self, key):
z = RBNode(key, RED, self.NIL, self.NIL, self.NIL)
y = self.NIL
x = self.root
while x is not self.NIL:
y = x
x = x.left if z.key < x.key else x.right
z.parent = y
if y is self.NIL:
self.root = z
elif z.key < y.key:
y.left = z
else:
y.right = z
self._fixup(z)
def _fixup(self, z):
while z.parent.color == RED:
if z.parent is z.parent.parent.left:
u = z.parent.parent.right
if u.color == RED:
z.parent.color = BLACK
u.color = BLACK
z.parent.parent.color = RED
z = z.parent.parent
else:
if z is z.parent.right:
z = z.parent
self.left_rotate(z)
z.parent.color = BLACK
z.parent.parent.color = RED
self.right_rotate(z.parent.parent)
else:
u = z.parent.parent.left
if u.color == RED:
z.parent.color = BLACK
u.color = BLACK
z.parent.parent.color = RED
z = z.parent.parent
else:
if z is z.parent.left:
z = z.parent
self.right_rotate(z)
z.parent.color = BLACK
z.parent.parent.color = RED
self.left_rotate(z.parent.parent)
self.root.color = BLACK
def verify(self):
if self.root.color != BLACK:
return False, -1, []
ino = []
def dfs(node):
if node is self.NIL:
return True, 1
if node.color == RED and (node.left.color == RED or node.right.color == RED):
return False, -1
ok_l, bh_l = dfs(node.left)
ino.append(node.key)
ok_r, bh_r = dfs(node.right)
if not (ok_l and ok_r) or bh_l != bh_r:
return False, -1
return True, bh_l + (1 if node.color == BLACK else 0)
ok, bh = dfs(self.root)
return ok, bh, ino
rbt = RBTree()
keys = [10, 20, 30, 15, 25, 5, 1, 8, 12, 18]
for k in keys:
rbt.insert(k)
ok, black_height, ino = rbt.verify()
expected = {
"root_is_black": True,
"all_five_rules_valid": True,
"black_height": 3,
"inorder_sorted": sorted(keys),
}
actual = {
"root_is_black": rbt.root.color == BLACK,
"all_five_rules_valid": ok,
"black_height": black_height,
"inorder_sorted": ino,
}
return {
"name": "red_black_tree_five_invariants",
"summary": "实现完整红黑树插入修复并校验五项核心颜色与黑高不变量",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_btree_and_bplus_range_query():
# 简明 B+ 树模型(阶 m=3,内部节点仅存路由键,数据仅存叶子且叶子形成有序链表)
class BPlusLeaf:
def __init__(self, items, nxt=None):
self.items = items # [(key, record)]
self.next = nxt
class BPlusInternal:
def __init__(self, keys, children):
self.keys = keys
self.children = children
# 构造已平衡的 3 阶 B+ 树(年龄索引:15,18 | 20,24 | 27,30 | 35,40)
l4 = BPlusLeaf([(35, "u7"), (40, "u8")])
l3 = BPlusLeaf([(27, "u5"), (30, "u6")], nxt=l4)
l2 = BPlusLeaf([(20, "u3"), (24, "u4")], nxt=l3)
l1 = BPlusLeaf([(15, "u1"), (18, "u2")], nxt=l2)
root = BPlusInternal([20, 27, 35], [l1, l2, l3, l4])
def range_query_bplus(r, lo, hi):
# 下探至首个可能包含 lo 的叶子
idx = 0
while idx < len(r.keys) and lo >= r.keys[idx]:
idx += 1
leaf = r.children[idx]
result = []
leaf_hops = 0
while leaf is not None:
leaf_hops += 1
for k, rec in leaf.items:
if k > hi:
return result, leaf_hops
if k >= lo:
result.append((k, rec))
leaf = leaf.next
return result, leaf_hops
rows, hops = range_query_bplus(root, 20, 30)
# 校验 3 阶 B 树节点结构:2 个键划分 3 个值域区间
btree_node_keys = [20, 40]
intervals = [("<20", 15 < btree_node_keys[0]), ("20..40", 20 < 30 < 40), (">40", 50 > btree_node_keys[1])]
expected = {
"btree_3order_key_child_ratio": [2, 3],
"btree_partitions_valid": True,
"bplus_between_20_30": [(20, "u3"), (24, "u4"), (27, "u5"), (30, "u6")],
"bplus_leaf_chain_hops": 3,
}
actual = {
"btree_3order_key_child_ratio": [len(btree_node_keys), len(btree_node_keys) + 1],
"btree_partitions_valid": all(ok for _, ok in intervals),
"bplus_between_20_30": rows,
"bplus_leaf_chain_hops": hops,
}
return {
"name": "btree_and_bplus_range_query",
"summary": "验证 3 阶 B 树值域划分规律及 B+ 树叶子有序链表范围查询(BETWEEN 20 AND 30)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_bst_degeneration_vs_avl_balance(),
case_avl_four_rotations_explicit(),
case_red_black_tree_five_invariants(),
case_btree_and_bplus_range_query(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。
入口文件:projects/data-structures-dsa-advanced-tree-lab/explore-dsa-advanced-tree.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dsa-advanced-tree.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202612a2641.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2650.zip