BST:插入、查询与 Rank 的增广设计
Algorithms:Binary Search Trees and BST Sort
本文逐段翻译 MIT 6.006 Fall 2011 Lecture 5《Binary Search Trees and BST Sort》,从 runway reservation 问题出发,说明为什么 BST 同时提供 binary-search navigation 与 pointer-based insertion,并介绍 search、insert、successor、BST sort,以及用 subtree size 增广 BST 来计算 rank。
TL;DR
- 问题:runway reservation 需要在
O(log n)内判断一个 landing time 是否与已有 reservation 相距至少k分钟,并支持插入与删除。 - BST invariant:对任意 node
x,left subtree 中的 keys 不大于key(x),right subtree 中的 keys 不小于key(x)。 - 核心操作:search、insert、
find-min、find-max和 successor 都沿 tree path 运行,复杂度为O(h);h是 tree height。 - BST sort:先把 elements 插入 BST,再按 inorder 顺序访问,就能得到 sorted order;但普通 BST 在有序输入上会退化为
O(n²)。 - Augmentation:给每个 node 保存 subtree size,可以在
O(h)内计算rank(t);更新字段只需跟随 insert/delete 的 path。
目录
| 章节 | 说明 |
|---|---|
| Lecture 5:Binary Search Trees and Runway Reservations | runway reservation 的问题定义 |
| 为什么已有 data structures 不够 | unsorted array、sorted array、linked list 与 heap 的取舍 |
| Binary Search Tree | node 结构与 BST invariant |
| BST insertion 与 k-minute check | 沿 search path 检查并插入 |
| BST operations | search、minimum、maximum 与 successor |
| BST sort | inorder traversal 与复杂度 |
| Augmented BST:rank | subtree size 与 rank 查询 |
| Unbalanced BST 的边界 | height 退化与 balanced BST |
| 小结 | 本讲要点 |
Lecture 5:Binary Search Trees and Runway Reservations
考虑一个只有一条 runway 的 airport。未来的 landing times 保存在一个 set R 中;时间 t 是连续的,k 是两架飞机之间必须保留的 safety interval,通常取 3 分钟。
当一架飞机希望在时间 t landing 时,系统必须满足:
1. t 不在过去;
2. R 中不存在一个 reservation,与 t 的距离小于 k;
3. 如果条件满足,就把 t 加入 R。
飞机 landing 后,系统还要从 R 中删除对应的 time。理想的 data structure 应该支持:
insert(t) 检查安全间隔并插入 t
delete(t) 删除已经完成的 reservation
并且每次操作都尽可能接近 O(log n),其中 n 是当前 reservation 数量。
为什么已有 data structures 不够
Unsorted array 或 linked list
把新 time 加到末尾只需要 O(1),但为了检查 safety interval,最坏情况下必须扫描全部 n 个 reservations,因此是 O(n)。
Sorted array
sorted array 可以用 binary search 找到第一个满足 R[i] ≥ t 的位置。只要检查这个位置及其相邻位置,就能在 O(log n) 的 search 之后完成 safety check。
问题在于真正插入 t 时,后面的 elements 必须整体向右移动;因此 array insertion 仍然是 O(n)。
Sorted linked list
linked list 在已知插入位置之后可以用 O(1) 插入,但 linked list 没有 random access,不能像 array 那样直接取中间位置,所以不能有效执行 binary search。
Heap 或 dictionary
heap 只保证 root 是 minimum 或 maximum,不能快速定位一个 key 的 predecessor 和 successor;为了检查 t 两侧最近的 reservation,最坏情况下仍然需要查看大量 elements。普通 hash table 同样不提供 ordered-neighbor 查询。
BST 的目标正是结合两种优势:像 binary search 一样沿 ordered path 缩小范围,又像 linked structure 一样在找到位置后用 pointer 插入 node。
Binary Search Tree
BST 是一个真正由 pointers 连接的 tree。每个 node 至少包含一个 key,以及指向 parent、left child 和 right child 的 pointers:
Node:
key
parent
left
right
BST invariant 是:对任意 node x:
如果 y 在 x 的 left subtree 中,则 key(y) ≤ key(x)
如果 y 在 x 的 right subtree 中,则 key(y) ≥ key(x)
这个条件约束的是整个 subtree,而不只是直接 children,所以它比 heap property 更强。duplicates 可以存在;如果需要区分相同 key,可以给 key 增加 tie-breaker,例如 46a 和 46b。
BST 与 heap 的表示方式也不同:heap 通常把一个 array 解释成 nearly complete tree;BST 的 tree shape 由 pointers 和插入顺序决定,不要求 nearly complete。
BST insertion 与 k-minute check
从空树开始依次插入 49、79、46 和 41,得到如下 BST:
49
/ \
46 79
/
41
现在尝试插入 42,设 k = 3。沿 BST search path 比较:
与 49 比较:|42 - 49| = 7,安全
与 46 比较:|42 - 46| = 4,安全
与 41 比较:|42 - 41| = 1,违反 safety interval
因此 42 不能被 reservation。尝试 45 时,在 node 46 处已经发现:
|45 - 46| = 1 < 3
所以同样拒绝。
如果 search path 上没有任何 reservation 违反 safety interval,最后到达一个空 child pointer,就可以在那里创建新 node:
BST-Insert(T, z):
p ← NIL
x ← root(T)
while x ≠ NIL:
p ← x
if key(z) < key(x):
x ← left(x)
else:
x ← right(x)
parent(z) ← p
if p = NIL:
root(T) ← z
else if key(z) < key(p):
left(p) ← z
else:
right(p) ← z
runway reservation 可以在这条 path 上同时做 k-minute check;如果 check 失败,不修改 tree。如果成功,就把新 node attach 到找到的 leaf position。若 tree height 为 h,search 和 insertion 都是 O(h)。
BST operations
Search
BST search 每次把目标 key 与当前 node 比较:相等则找到;目标更小就进入 left subtree;目标更大就进入 right subtree。每一步都丢弃一个不可能包含目标的 subtree,因此最多访问一条 root-to-leaf path:
BST-Search(x, k):
if x = NIL or key(x) = k:
return x
if k < key(x):
return BST-Search(left(x), k)
else:
return BST-Search(right(x), k)
复杂度为 O(h)。
Minimum 与 maximum
BST 中最小 key 位于最左侧 path 的末端,最大 key 位于最右侧 path 的末端:
BST-Minimum(x):
while left(x) ≠ NIL:
x ← left(x)
return x
BST-Maximum(x):
while right(x) ≠ NIL:
x ← right(x)
return x
两者都只沿一条 path 行走,因此复杂度为 O(h)。
Successor
一个 node x 的 successor 是大于 key(x) 的最小 key。如果 x 有 right subtree,successor 是该 subtree 的 minimum;如果没有 right subtree,就沿 parent pointers 向上,直到从某个 node 的 left side 回到它的 ancestor。
BST-Successor(x):
if right(x) ≠ NIL:
return BST-Minimum(right(x))
p ← parent(x)
while p ≠ NIL and x = right(p):
x ← p
p ← parent(p)
return p
这个过程最多上行并下行 tree height,因此是 O(h)。
BST sort
BST 也可以用来 sorting:把所有 input elements 插入一棵 BST,然后对 tree 做 inorder traversal。BST invariant 保证:先访问 left subtree,再访问 root,最后访问 right subtree,输出顺序就是 nondecreasing order。
BST-Sort(A):
T ← empty BST
for each element a in A:
BST-Insert(T, a)
Inorder-Tree-Walk(root(T))
如果 tree 保持 height O(log n),n 次 insertion 的总复杂度是 O(n log n),inorder traversal 是 Θ(n)。但普通 BST 不保证 balance:若 input 已经 sorted,树会退化成 linked list,插入总成本为:
1 + 2 + 3 + ... + n = Θ(n²)
因此 BST sort 的效率取决于 tree shape;下一讲的 balanced BST 将解决这个问题。
Augmented BST:rank
考虑一个新的 query:
rank(t) = R 中小于或等于 t 的 reservation 数量
普通 BST 可以通过 inorder traversal 计算 rank,但那需要 O(n)。要在 O(h) 内完成,需要给每个 node 增加一个字段:该 node subtree 中的 node 数量,记为 size(x)。
例如 tree 包含 43、46、49、64、79、83:
49(6)
/ \
46(2) 79(3)
/ / \
43(1) 64(1) 83(1)
括号中的数字是 subtree size。leaf 的 size 为 1;79 的 size 为 3;root 49 的 size 为 6。
更新 subtree size
插入一个新 leaf 时,新 node 的 size 初始化为 1;沿普通 BST insertion path 向下时,访问到的每个 ancestor 的 size 增加 1。删除 node 时,pointer rewiring 完成后,对受影响的 ancestors 减少 1。
对于 runway reservation,如果 k-minute check 失败,则不应修改任何 size;如果 reservation 被接受,就沿同一条 path 更新这些字段。更新不会改变渐进复杂度,仍然是 O(h)。
在 O(h) 内计算 rank
查询 rank(t) 时,可以像插入 t 一样从 root 向下。维护一个 accumulator:
Rank(T, t):
x ← root(T)
rank ← 0
while x ≠ NIL:
if t < key(x):
x ← left(x)
else:
rank ← rank + 1 + size(left(x))
if t = key(x):
return rank
x ← right(x)
return rank
当 t 大于当前 key(x) 时,x 本身以及 x 的整个 left subtree 都不大于 t,所以可以一次性把 1 + size(left(x)) 加入 accumulator,然后向 right subtree 继续。遇到相等 key 时,加入当前 node 和 left subtree 后即可返回。
以上例计算 rank(79):
在 49:加入 1 + size(left(49)) = 1 + 2
在 79:加入 1 + size(left(79)) = 1 + 1
总数:5
这 5 个 keys 是 43、46、49、64、79。每次循环只沿一条 path 前进,所以 Rank 的复杂度为 O(h)。
Unbalanced BST 的边界
BST 的所有复杂度都以 height h 表示。当 tree reasonably balanced 时,h = O(log n);但普通 insertion order 可能产生极度 unbalanced 的 tree,此时 h = O(n),search、insert、delete 和 rank 都可能退化为线性时间。
因此,BST invariant 本身还不够。要稳定获得 O(log n),必须额外维护 balance invariant。AVL tree 等 balanced BST 会在 insertion 和 deletion 后通过 rotations 修复 height;这正是下一讲的主题。
小结
BST 用 ordered subtree invariant 把 binary search 的导航方式与 pointer-based insertion 结合起来。它适合处理需要 predecessor、successor 和 ordered-neighbor 的问题,例如 runway reservation;通过 inorder traversal,它也能实现 BST sort。需要牢记的是,普通 BST 的复杂度是 O(h) 而不是自动的 O(log n)。通过增加 subtree size,可以在不改变基本 search path 的情况下实现 O(h) 的 rank query;但要让这个上界稳定成立,仍然需要 balanced BST。
参考资料
评论 (0)