平衡樹:AVL 和紅黑樹
平衡樹插入後調整形狀,讓高度保持 O(log n):AVL 樹左右高度差超過 1 就旋轉,std::set 和 std::map 裡面是紅黑樹,資料庫索引用 B+ 樹。
第 4 章講二叉搜尋樹時看到:300 個數按順序插入二叉搜尋樹,高度是 300,查詢退化成 O(n)。問題不在二叉搜尋樹本身,而在它不管自己長成什麼樣。平衡樹在每次插入、刪除以後檢查形狀,歪了就調整,保證高度一直是 O(log n)。
AVL 樹:左右高度最多差 1
AVL 樹(以兩位發明者命名)是最早的平衡樹。它在二叉搜尋樹的規矩上再加一條:每個結點的左右子樹高度差(平衡因子)只能是 −1、0、1。插入一個數以後,從它往上走,第一個平衡因子變成 ±2 的結點就是失衡的地方,在那裡旋轉一次就能修好。
平衡因子從新插入的結點往上一個個重新算。用依次插入 10、20、30 看一看:
往空的 AVL 樹裡依次插入 5、3、8、1(都不用旋轉)。根 5 的平衡因子是多少?
是不是平衡的
✓判斷一棵二元樹是不是每個結點的左右高度差都不超過 1。技巧:check 返回高度,發現不平衡就返回 -1,一路往上傳。
1 0
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), left(l), right(r) {}9};10 11int check(Node* t) {12 // 空樹:0;左或右是 -1:-1;高度差 > 1:-1;否則返回高度13 return 0;14}15 16int main() {17 Node* a = new Node(1, new Node(2, new Node(4)), new Node(3));18 Node* b = new Node(1, new Node(2, new Node(4, new Node(5))), new Node(3));19 cout << (check(a) != -1) << " " << (check(b) != -1) << endl;20 return 0;21}
四種失衡,兩種旋轉
插入以後從新結點往上找,第一個平衡因子變成 ±2 的結點就是要修的地方。修法只有兩種動作:右旋和左旋。
失衡分四種,按「新結點插在失衡結點的哪個孩子的哪一邊」命名:
| 失衡 | 新結點插在 | 怎麼修 |
|---|---|---|
| LL | 左孩子的左子樹 | 右旋一次 |
| RR | 右孩子的右子樹 | 左旋一次 |
| LR | 左孩子的右子樹 | 先對左孩子左旋,再對自己右旋 |
| RL | 右孩子的左子樹 | 先對右孩子右旋,再對自己左旋 |
右旋就是:左孩子提上來當根,原來的根變成它的右孩子,左孩子原來的右子樹掛到原來的根的左邊。左旋反過來。
往空的 AVL 樹裡依次插入 30、10、20。失衡是哪一種,轉完以後根是幾?
把左旋 rot_left 的 6 行排好:右孩子 r 提上來,t 變成 r 的左孩子。
fix(t);r->left = t;Node* r = t->right;return r;fix(r);t->right = r->left;
2 1 3 2
寫右旋
✓補全 rot_right:左孩子 l 提上來,t 變成 l 的右孩子,l 原來的右子樹掛到 t 的左邊;先更新 t 的高度,再更新 l 的。
5 3 1 8 6 9 高度 3
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), h(1), left(l), right(r) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* make(int v, Node* l = nullptr, Node* r = nullptr) {15 Node* n = new Node(v, l, r);16 fix(n);17 return n;18}19 20Node* rot_right(Node* t) {21 // l = t->left;t->left = l->right;l->right = t;fix(t);fix(l);返回 l22 return t;23}24 25void pre(Node* t) {26 if (!t) return;27 cout << t->val << ' ';28 pre(t->left);29 pre(t->right);30}31 32int main() {33 // 8 的左邊 5(3(1, _), 6) 比右邊 9 高 2:LL34 Node* t = make(8, make(5, make(3, make(1)), make(6)), make(9));35 t = rot_right(t);36 pre(t);37 cout << "\n高度 " << t->h << endl;38 return 0;39}
寫成 C++:插入完就檢查
結點裡多存一個 h:以它為根的子樹有多高。旋轉只改三根指標,改完先更新下面那個結點的高度,再更新上面那個。
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h; // h:以它為根的子樹高度7 Node *left, *right;8 Node(int v) : val(v), h(1), left(nullptr), right(nullptr) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { // 左孩子提上來15 Node* l = t->left;16 t->left = l->right;17 l->right = t;18 fix(t);19 fix(l);20 return l;21}22 23Node* rot_left(Node* t) { // 右孩子提上來24 Node* r = t->right;25 t->right = r->left;26 r->left = t;27 fix(t);28 fix(r);29 return r;30}31 32Node* insert(Node* t, int v) {33 if (!t) return new Node(v);34 if (v < t->val) t->left = insert(t->left, v);35 else t->right = insert(t->right, v);36 fix(t);37 int bf = H(t->left) - H(t->right); // 平衡因子38 if (bf > 1 && v < t->left->val) return rot_right(t); // LL39 if (bf < -1 && v > t->right->val) return rot_left(t); // RR40 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); } // LR41 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); } // RL42 return t;43}44 45void destroy(Node* t) { // 後序:先刪孩子,再刪自己46 if (!t) return;47 destroy(t->left);48 destroy(t->right);49 delete t;50}51 52int main() {53 Node* t = nullptr;54 for (int i = 1; i <= 1000; i++)55 t = insert(t, i); // 按順序插入:普通二叉搜尋樹會高 100056 cout << "AVL 樹:1000 個數,高度 " << t->h << ",根是 " << t->val << endl;57 destroy(t);58 return 0;59}
AVL 樹:1000 個數,高度 10,根是 512
按順序插入 1000 個數,AVL 樹的高度只有 10,和 log₂ 1000 差不多。每次插入最多旋轉兩次,查詢、插入、刪除都是 O(log n)。new 出來的結點最後用 destroy 後序釋放;這一課的猜一猜和練習為了短,省掉了這一步。
AVL 樹裡依次插入 1 到 7,前序遍歷印出什麼?
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v) : val(v), h(1), left(nullptr), right(nullptr) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { Node* l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }15Node* rot_left(Node* t) { Node* r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }16 17Node* insert(Node* t, int v) {18 if (!t) return new Node(v);19 if (v < t->val) t->left = insert(t->left, v);20 else t->right = insert(t->right, v);21 fix(t);22 int bf = H(t->left) - H(t->right);23 if (bf > 1 && v < t->left->val) return rot_right(t);24 if (bf < -1 && v > t->right->val) return rot_left(t);25 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }26 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }27 return t;28}29 30void pre(Node* t) {31 if (!t) return;32 cout << t->val << ' ';33 pre(t->left);34 pre(t->right);35}36 37int main() {38 Node* t = nullptr;39 for (int i = 1; i <= 7; i++) t = insert(t, i);40 pre(t);41 cout << endl;42 return 0;43}
LL 的情況(新結點在左孩子的左邊)該呼叫哪個旋轉?在空格裡填上,讓依次插入 7 到 1 的樹平衡。
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct Node {6 int val, h;7 Node *left, *right;8 Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), h(1), left(l), right(r) {}9};10 11int H(Node* t) { return t ? t->h : 0; }12void fix(Node* t) { t->h = max(H(t->left), H(t->right)) + 1; }13 14Node* rot_right(Node* t) { Node* l = t->left; t->left = l->right; l->right = t; fix(t); fix(l); return l; }15Node* rot_left(Node* t) { Node* r = t->right; t->right = r->left; r->left = t; fix(t); fix(r); return r; }16 17Node* insert(Node* t, int v) {18 if (!t) return new Node(v);19 if (v < t->val) t->left = insert(t->left, v);20 else t->right = insert(t->right, v);21 fix(t);22 int bf = H(t->left) - H(t->right);23 if (bf > 1 && v < t->left->val) return (t);24 if (bf < -1 && v > t->right->val) return rot_left(t);25 if (bf > 1) { t->left = rot_left(t->left); return rot_right(t); }26 if (bf < -1) { t->right = rot_right(t->right); return rot_left(t); }27 return t;28}29 30void pre(Node* t) {31 if (!t) return;32 cout << t->val << ' ';33 pre(t->left);34 pre(t->right);35}36 37int main() {38 Node* t = nullptr;39 for (int i = 7; i >= 1; i--) t = insert(t, i);40 pre(t);41 cout << endl;42 return 0;43}
rot_right。填 rot_left 會去拿空的右孩子,程式停在那裡。B 樹:一個結點放很多個鍵
資料多到放不進記憶體、要存在磁碟上時,情況變了:從磁碟讀一次要幾毫秒,比記憶體慢十萬倍,而且一次總是讀一整塊(幾 KB)。這時最要緊的是讀磁碟的次數,也就是樹的高度。
B 樹的辦法是讓每個結點放很多個鍵、有很多個孩子:一個結點正好是一個磁碟塊,裡面的鍵排好序,夾在兩個鍵中間的孩子,存的就是介於這兩個鍵之間的值。
一個結點放 1000 個鍵時,三層就能放下 10 億個鍵(1000 × 1000 × 1000),找任何一個都只讀 3 次磁碟。B 樹還保證所有葉子在同一層,插入時結點滿了就分裂成兩個、把中間的鍵提到父親裡,所以它永遠是平衡的。
在這一關開頭那棵 3 階 B 樹裡找 61,要讀幾次磁碟?
B+ 樹,和該選哪種樹
資料庫要的不只是「找一個」,還常常要「找一段」。B+ 樹就是為這個改出來的。
B+ 樹是 B 樹的變種:所有資料都放在葉子上,內部結點只放用來指路的鍵,葉子之間再用鏈結串列串起來。這樣按範圍查(比如「成績在 60 到 80 之間的」)只要找到起點、順著鏈結串列往後讀。MySQL 的 InnoDB 儲存引擎、大多數檔案系統的索引都是 B+ 樹。
| 結構 | 每個結點 | 適合 | 用在哪 |
|---|---|---|---|
| AVL 樹 | 1 個鍵,2 個孩子 | 記憶體裡,查得多 | 教材、考試 |
| 紅黑樹 | 1 個鍵,2 個孩子 | 記憶體裡,插刪也多 | std::set、std::map、Java TreeMap |
| B 樹 / B+ 樹 | 很多個鍵和孩子 | 磁碟上,讀一次是一整塊 | 資料庫索引、檔案系統 |
考試裡: AVL 的題會給一個插入序列,問每一步有沒有失衡、是哪一種、轉完的樹長什麼樣,或者問「高度為 h 的 AVL 樹最少有幾個結點」(N(h) = N(h − 1) + N(h − 2) + 1,N(1) = 1,N(2) = 2)。B 樹一般只考概念:m 階 B 樹每個結點最多 m 個孩子、除根以外至少 ⌈m / 2⌉ 個,所有葉子在同一層。
5 階 B 樹裡,除了根,每個結點至少有幾個孩子?
要從幾百萬條記錄裡找出成績在 60 到 80 之間的,用哪種結構最合適?
用 STL 寫
C++ 裡不用自己寫平衡樹:std::set、std::map(還有 multiset、multimap)裡面都是紅黑樹。紅黑樹給每個結點塗上紅色或黑色,守住四條規矩:
- 根是黑的。
- 紅結點的孩子都是黑的(不會有兩個紅的連在一起)。
- 從任何一個結點往下走到空位,每條路上的黑結點一樣多。
- 空位(
nullptr)算黑的。
由 2 和 3,最長的路(紅黑相間)不會超過最短的路(全黑)的兩倍,所以高度不超過 2 log₂(n + 1)。它沒有 AVL 那麼勻稱,但插入、刪除時轉得更少(插入最多轉兩次,刪除最多三次),大部分時候只是改改顏色。這正是標準庫要的:插刪和查詢都多的時候,總的來說更快。
還是按 1, 2, …, 1000 的順序插進去,給 set 一個會數數的比較函式,看查詢每個數要比較幾次:
1#include <iostream>2#include <set>3using namespace std;4 5long cmps = 0;6 7struct CountLess { // 和 < 一樣,只是每比一次記一下8 bool operator()(int a, int b) const {9 cmps++;10 return a < b;11 }12};13 14int main() {15 set<int, CountLess> s;16 for (int i = 1; i <= 1000; i++) s.insert(i); // 按順序插:普通 BST 會變成鏈17 cout << "插入 1000 個,一共比較 " << cmps << " 次" << endl;18 19 long worst = 0, total = 0;20 for (int i = 1; i <= 1000; i++) {21 cmps = 0;22 s.find(i);23 total += cmps;24 if (cmps > worst) worst = cmps;25 }26 cout << "查詢:平均 " << total / 1000.0 << " 次,最多 " << worst << " 次" << endl;27 return 0;28}
插入 1000 個,一共比較 16479 次 查詢:平均 11.389 次,最多 18 次
插入平均每個 16 次多;查詢平均 11 次多、最多 18 次(find 先往下走到底找「第一個不小於 x 的」,再多比一次),沒有超過紅黑樹的上限 2 log₂ 1000 ≈ 20。按順序插的普通二叉搜尋樹,查最後一個要比 1000 次。
有了平衡,set / map 就是「一直有序、改起來也快」的容器。比如記一張按時間排的日程表,隨時加、隨時刪,還要問「某個時刻之後的下一件事」:
1#include <iostream>2#include <map>3#include <string>4using namespace std;5 6int main() {7 map<int, string> plan; // 時間(分鐘)→ 事情,按時間排8 plan[540] = "上課";9 plan[720] = "午飯";10 plan[600] = "開會";11 plan[900] = "跑步";12 plan.erase(600); // 會取消了:O(log n)13 plan[840] = "答疑";14 15 for (auto& kv : plan) // 遍歷:從小到大16 cout << kv.first / 60 << ":" << (kv.first % 60 < 10 ? "0" : "") << kv.first % 6017 << " " << kv.second << endl;18 19 auto it = plan.lower_bound(750); // 12:30 之後的下一件事20 cout << "12:30 之後:" << it->second << endl;21 if (it != plan.begin()) {22 --it; // 往回一個:12:30 之前最近的一件23 cout << "12:30 之前:" << it->second << endl;24 }25 cout << "最早 " << plan.begin()->second << ",最晚 " << plan.rbegin()->second << endl;26 return 0;27}
9:00 上課 12:00 午飯 14:00 答疑 15:00 跑步 12:30 之後:答疑 12:30 之前:午飯 最早 上課,最晚 跑步
lower_bound 是 map 自己的成員函式,從根往下走一條路,O(log n);拿到迭代器以後 --it、++it 就是中序裡的前一個、後一個。
| 操作 | set / map(紅黑樹) | 有序 vector | 普通 BST(最壞) |
|---|---|---|---|
查詢 find、count | O(log n) | O(log n)(二分) | O(n) |
| 插入、刪除 | O(log n) | O(n):要挪 | O(n) |
lower_bound(x) | O(log n),用成員函式 | O(log n) | O(n) |
| 按順序遍歷 | O(n) | O(n) | O(n) |
| 最小、最大 | O(1):begin()、rbegin() | O(1) | O(n) |
點這段程式碼的「視覺化」單步走,s 會畫成它裡面真正的紅黑樹:紅結點、黑結點、每次插入後怎麼變色、怎麼轉,和 g++ 裡的一模一樣:
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s;7 int a[] = {40, 20, 60, 10, 30, 50, 70, 25};8 for (int x : a) s.insert(x);9 cout << s.size() << " " << *s.begin() << " " << *s.rbegin() << "\n";10 return 0;11}
8 10 70
面試裡: 「std::map 底層是什麼?」答紅黑樹,再說清楚為什麼不用 AVL:查詢差不多一樣快,插刪時旋轉更少。手寫紅黑樹幾乎不會考(插入的情況太多),能說出那幾條規矩、知道高度 ≤ 2 log₂(n + 1) 就夠了。要不要順序是選 map 還是 unordered_map 的分界線:不要順序、只按「等於」查,雜湊表平均 O(1) 更快。
紅黑樹和 AVL 樹比,好在哪裡?
set 插入、刪除以後,印出什麼?
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s = {40, 20, 60, 10, 30};7 s.insert(20);8 s.erase(60);9 auto it = s.lower_bound(25);10 cout << s.size() << " " << *it << " " << *s.rbegin() << endl;11 return 0;12}
set 裡不會有重複的,再插一個 20 什麼也不變;刪掉 60 以後剩 10 20 30 40,4 個。lower_bound(25) 是第一個不小於 25 的:30。rbegin() 指向最大的那個:40。小結
平衡樹:歪了就轉,高度保持 O(log n)
- AVL:每個結點左右高度差 ≤ 1,插入後找第一個失衡的結點
- LL 右旋,RR 左旋,LR 先左後右,RL 先右後左
- 紅黑樹:沒有兩個紅的相連、每條路黑結點一樣多,高度 ≤ 2 log₂(n + 1)
- set / map 就是紅黑樹:插、刪、查、lower_bound 都是 O(log n),遍歷有序
- B 樹 / B+ 樹:一個結點很多鍵,樹很矮,少讀磁碟;資料庫索引
1Node* rot_right(Node* t) {2 Node* l = t->left;3 t->left = l->right; l->right = t;4 fix(t); fix(l);5 return l;6}