蓝色天空网mbsky.com · 知识 · 实践 · 创造数据结构与算法 · 本地阅读预览
教程 / 计算机基础 / 数据结构与算法

高级树结构

系统剖析二叉搜索树退化风险,深入讲解 AVL 树平衡因子与 LL/RR/LR/RL 四种旋转、红黑树五项染色规则与插入修复,以及面向磁盘 I/O 与范围查询的 B 树和 B+ 树。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

自平衡树动机:避免 BST 退化

普通二叉搜索树(BST)在随机插入下接近平衡,但一旦按递增或字母序依次插入(如 `A...`, `B...`, `C...`),树会退化为一条斜链,检索效率由 `O(log n)` 跌落至 `O(n)`。AVL 树、红黑树、B 树与 B+ 树四类高级树结构通过旋转重平衡或多路扇出策略,将增删查稳定维持在 `O(log n)` 量级。

AVL 树:严格高度平衡与四种旋转

AVL 树(Adelson-Velsky 与 Landis 提出)是最早的自平衡二叉搜索树,要求任意节点的平衡因子 `左子树高度 - 右子树高度` 严格落在 `-1`、`0`、`1` 范围内。当增删引发某节点平衡因子变为 `+2` 或 `-2` 时,按失衡形态执行四种旋转恢复平衡:LL(左左)单右旋、RR(右右)单左旋、LR(左右)先左旋后右旋、RL(右左)先右旋后左旋;旋转时须先更新原下沉节点高度再更新新根高度。本站脚本实测顺序插入 `1..15` 时普通 BST 高度退化为 `15`,而完整 AVL 树始终保持高度 `4`。

红黑树:五项规则与工程权衡

红黑树以略微宽松的平衡条件换取更少的增删旋转开销,被 Java `TreeMap`/`TreeSet` 与 C++ STL `map`/`set` 广泛采用。其五项核心规则为:(1)节点非红即黑;(2)根为黑色;(3)所有 NIL 空叶节点为黑色;(4)红节点的两个子节点必为黑色(无连续红节点);(5)任一节点到其各叶子的路径含相同数量黑节点(黑高一致),从而保证最长路径不超过最短路径的两倍。新节点默认染红插入,若与红父冲突则按叔节点颜色分情况变色或旋转并将冲突上移至根部消除。

B 树与 B+ 树:面向磁盘页与数据库索引

当索引规模远超内存须落盘存储时,降低磁盘 I/O 次数成为首要目标。m 阶 B 树是多路平衡搜索树:每个节点至多 m 个子节点、非根非叶节点至少 `⌈m/2⌉` 个子节点、非叶根至少 2 个子节点、全部叶子同层,且含 k 个子节点的内部节点存 `k - 1` 个键用于划分子树值域(如 3 阶节点存 2 键划 3 区间)。高扇出让树形“矮胖”,极大减少查询经过的磁盘页数。

B+ 树在 B 树之上做出两项关键升级:所有数据记录(或记录指针)仅存放于叶子节点,内部节点只存路由键以容纳更高扇出;全部叶子通过双向指针串联为有序链表。这使 B+ 树具备查询路径等长稳定、空间利用率更高、契合磁盘按页预读以及极强范围查询能力(如 `WHERE age BETWEEN 20 AND 30` 定位起点叶子后顺链扫描即可),成为现代关系型数据库索引的事实标准。

AVL 树核心特点总结

特点技术说明
严格平衡左右子树高度差严格 <= 1,树高紧贴 log₂ n,查找极快
调整频繁插入与删除后可能沿祖先路径触发多次旋转
适用场景读远多于写的内存查找表与静态热索引

AVL 树与红黑树横向对比

对比维度AVL 树红黑树
平衡标准严格高度平衡(高度差 <= 1)近似平衡(最长路径 <= 2×最短路径)
查找性能树高更低,极限查找略优同为 O(log n),略多 1~2 层比较
插入/删除可能频繁旋转恢复严格平衡旋转次数受常数上界约束,综合写入更快
适用场景高频查询、低频变更场景读写均衡的标准库有序容器与内核调度

B+ 树相比 B 树的四大核心优势

优势原理解释
更稳定的查询效率所有查询均落至同层叶子节点,I/O 路径长度一致
更高的空间利用率内部节点不存完整记录,单页可放更多路由键,树更矮
强大的范围查询定位下界叶子后沿有序叶链表顺序扫描,无需反复回溯
更适合磁盘预读节点尺寸对齐磁盘页块,单次 I/O 载入海量分支键

四种经典高级树结构总览

树结构核心目标关键特性典型应用
AVL 树极致内存查找速度高度严格平衡,LL/RR/LR/RL 旋转频繁读多写少内存查找表
红黑树读写综合性能均衡五项染色规则维系近似平衡,旋转开销低语言标准库 Map/Set、进程调度
B 树减少磁盘随机 I/O多路平衡,数据可存于内部与叶节点部分文件系统与早期存储引擎
B+ 树数据库点查与范围索引数据仅存叶子、叶子成有序链表、扇出更高MySQL InnoDB、PostgreSQL 等数据库索引

实测 BST 退化与 AVL 四种旋转、红黑树五项不变量及 B+ 树叶链表范围查询

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 验证 1..15 顺序插入 BST 高度 15 对 AVL 高度 4、LL/RR/LR/RL 旋转、红黑树全部五条性质及 B+ 树 BETWEEN 20 AND 30 扫描全部通过。
实测 BST 退化与 AVL 四种旋转、红黑树五项不变量及 B+ 树叶链表范围查询

所需环境:Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。

当前源码 SHA256:bb8b5d5ebce4d9f61d3cec6870d1cfccf0bf7ad44afcd11285b025b6eaf9e776

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载高级树结构实验

所需环境:Windows x64、CPython 3.12.14 本地离线算法与数据结构实测环境(标准库确定性脚本)。

ZIP SHA256:15bc38c846c5429c8315f798565011d33bebee824d20740cfa9d07cc613ba415

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

数据库索引为何普遍选用 B+ 树而不是二叉树(AVL/红黑树)?

展开参考解答

二叉树单节点仅 2 路分支,千万级记录树高超过 23 层,意味着二十余次磁盘随机 I/O;B+ 树单页节点可容纳数百至上千路由键,3~4 层即可索引数千万行,且叶子链表天然加速范围查询。

规范与官方依据