二叉搜尋樹和 set / map
二叉搜尋樹左子樹都更小、右子樹都更大,查詢和插入只走一條從根往下的路:平衡時 O(log n),按順序插入變成鏈時 O(n);std::set 和 std::map 用紅黑樹保持 O(log n)。
有序陣列可以二分查詢,O(log n),但插入一個數要把後面的都往後挪,O(n)。鏈結串列插入只改兩個指標,可找一個數要從頭走。能不能找和插都快?二叉搜尋樹(BST)就是這個辦法:把二分查詢的「中間那個」直接做成樹的結點。
左邊都小,右邊都大
二叉搜尋樹的規矩只有一條:每個結點的左子樹裡都比它小,右子樹裡都比它大。所以找一個數時,和當前結點比一下就知道往哪邊走,另一邊整個都不用看。
1TreeNode* find(TreeNode* t, int v) {2 while (t && t->val != v)3 t = v < t->val ? t->left : t->right;4 return t;5}
查詢和插入都只走一條從根往下的路,比較次數最多是樹的高度。樹長得勻稱時高度約 log₂ n,就是 O(log n);還有一個好性質:中序遍歷二叉搜尋樹,得到的正好是從小到大的序列。
在這棵二叉搜尋樹裡找 5,要和幾個結點比過,才知道 5 不在樹裡?
1 82 / \3 3 104 / \ \5 1 6 146 / \7 4 7
選一個填進空格,讓 find 找得到 7、找不到 5,程式顯示 1 0。
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11 if (t == nullptr) return new TreeNode(v);12 if (v < t->val) t->left = insert(t->left, v);13 else if (v > t->val) t->right = insert(t->right, v);14 return t;15}16 17TreeNode* find(TreeNode* t, int v) {18 while (t && t->val != v)19 t = v < t->val ? : t->right;20 return t;21}22 23int main() {24 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};25 TreeNode* t = nullptr;26 for (int x : a) t = insert(t, x);27 cout << (find(t, 7) != nullptr) << " " << (find(t, 5) != nullptr) << "\n";28 return 0;29}
t->left 走。填 t->right 就把方向弄反了,7 也找不到;填 t 原地不動,迴圈永遠停不下來。最小值和最大值
✓補全 min_val 和 max_val:最小的在最左邊,最大的在最右邊。
20 80
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11 if (t == nullptr) return new TreeNode(v);12 if (v < t->val) t->left = insert(t->left, v);13 else if (v > t->val) t->right = insert(t->right, v);14 return t;15}16 17int min_val(TreeNode* t) {18 // 一直往左走,走到沒有左孩子19 return t->val;20}21 22int max_val(TreeNode* t) {23 // 一直往右走24 return t->val;25}26 27int main() {28 int a[] = {50, 30, 70, 20, 40, 60, 80, 35, 65};29 TreeNode* t = nullptr;30 for (int x : a) t = insert(t, x);31 cout << min_val(t) << " " << max_val(t) << endl;32 return 0;33}
是不是二叉搜尋樹
✓只比較「左孩子 < 自己 < 右孩子」是不夠的:左子樹裡所有結點都要比自己小。補全 ok(t, lo, hi):t 裡所有值都要在 (lo, hi) 之間。
1 0
1#include <iostream>2#include <climits>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)9 : val(v), left(l), right(r) {}10};11 12bool ok(TreeNode* t, long long lo, long long hi) {13 // 空樹是;自己不在 (lo, hi) 裡就不是;左子樹的上限變成自己,右子樹的下限變成自己14 return true;15}16 17int main() {18 TreeNode* good = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)), new TreeNode(10));19 // 9 在 8 的左子樹裡,但比 8 大:每個結點和孩子比都沒問題20 TreeNode* bad = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(9)), new TreeNode(10));21 cout << ok(good, LLONG_MIN, LLONG_MAX) << " " << ok(bad, LLONG_MIN, LLONG_MAX) << endl;22 return 0;23}
插入:走到空位就放下
插入和查詢走的是同一條路:從根開始,比當前結點小就往左,大就往右,走到空位(nullptr)就把新結點放在那裡。新結點總是掛成一片葉子,原來的結點一個都不用動。
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11 if (t == nullptr) return new TreeNode(v); // 走到空位:就放這裡12 if (v < t->val)13 t->left = insert(t->left, v);14 else if (v > t->val)15 t->right = insert(t->right, v);16 return t; // 一樣大的不放第二次17}18 19TreeNode* find(TreeNode* t, int v) {20 while (t && t->val != v)21 t = v < t->val ? t->left : t->right;22 return t;23}24 25void in(TreeNode* t) {26 if (!t) return;27 in(t->left);28 cout << t->val << ' ';29 in(t->right);30}31 32void destroy(TreeNode* t) {33 if (!t) return;34 destroy(t->left);35 destroy(t->right);36 delete t;37}38 39int main() {40 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};41 TreeNode* t = nullptr;42 for (int x : a)43 t = insert(t, x);44 in(t);45 cout << "\n找 7:" << (find(t, 7) ? "有" : "沒有")46 << ",找 5:" << (find(t, 5) ? "有" : "沒有") << endl;47 destroy(t);48 return 0;49}
1 3 4 6 7 8 10 14 找 7:有,找 5:沒有
insert 返回新的子樹根,呼叫的地方寫 t->left = insert(t->left, v):只有走到空位那一次真的 new 了結點,其他層原樣把自己交回去。這是寫樹的遞迴時最常用的寫法。
依次插入 5 2 8 1 4 9,再前序遍歷,印出什麼?
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11 if (t == nullptr) return new TreeNode(v);12 if (v < t->val) t->left = insert(t->left, v);13 else if (v > t->val) t->right = insert(t->right, v);14 return t;15}16 17void pre(TreeNode* t) {18 if (!t) return;19 cout << t->val << ' ';20 pre(t->left);21 pre(t->right);22}23 24int main() {25 int a[] = {5, 2, 8, 1, 4, 9};26 TreeNode* t = nullptr;27 for (int x : a) t = insert(t, x);28 pre(t);29 cout << endl;30 return 0;31}
往空樹裡依次插入 40 20 60 10 30 50 70 35,35 掛在哪裡?
刪除:三種情況
刪除比插入麻煩,因為刪掉的結點下面可能還掛著東西:
- 葉子:直接
delete,父親的指標改成nullptr。 - 只有一個孩子:讓孩子頂上來接它的位置。
- 兩個孩子都有:找它右子樹裡最小的那個(叫後繼,中序裡緊挨在它後面),把後繼的值抄過來,再去右子樹裡刪掉後繼。後繼一定沒有左孩子,所以刪它是情況 1 或 2。
情況 1 和 2 可以合成一句:拿出那個可能為空的孩子,delete 自己,把孩子交回給父親。
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}8};9 10TreeNode* insert(TreeNode* t, int v) {11 if (t == nullptr) return new TreeNode(v);12 if (v < t->val) t->left = insert(t->left, v);13 else if (v > t->val) t->right = insert(t->right, v);14 return t;15}16 17TreeNode* erase(TreeNode* t, int v) {18 if (t == nullptr) return nullptr; // 沒找到19 if (v < t->val) {20 t->left = erase(t->left, v);21 } else if (v > t->val) {22 t->right = erase(t->right, v);23 } else if (t->left == nullptr || t->right == nullptr) {24 TreeNode* child = t->left ? t->left : t->right; // 情況 1、225 delete t;26 return child;27 } else { // 情況 3:找後繼28 TreeNode* s = t->right;29 while (s->left) s = s->left;30 t->val = s->val;31 t->right = erase(t->right, s->val);32 }33 return t;34}35 36void pre(TreeNode* t) {37 if (!t) return;38 cout << t->val << ' ';39 pre(t->left);40 pre(t->right);41}42 43int main() {44 int a[] = {8, 3, 10, 1, 6, 14, 4, 7};45 TreeNode* t = nullptr;46 for (int x : a) t = insert(t, x);47 t = erase(t, 3); // 兩個孩子48 cout << "刪 3: ";49 pre(t);50 t = erase(t, 10); // 一個孩子51 cout << "\n刪 10:";52 pre(t);53 t = erase(t, 1); // 葉子54 cout << "\n刪 1: ";55 pre(t);56 cout << endl;57 return 0;58}
刪 3: 8 4 1 6 7 10 14 刪 10:8 4 1 6 7 14 刪 1: 8 4 6 7 14
在這棵樹裡刪掉根 50(用後繼頂替)。刪完以後,根是幾?
1 502 / \3 30 704 / \ / \5 20 40 60 806 / \7 35 65
還是這棵樹,這次刪掉 30(用後繼頂替)。30 的位置換成了幾?
1 502 / \3 30 704 / \ / \5 20 40 60 806 / \7 35 65
刪除一個兩個孩子都有的結點:把這四步排好。
在右子樹裡刪掉原來的後繼(它沒有左孩子)到它的右子樹裡,一路往左走到最小的那個:後繼找到要刪的結點把後繼的值抄到要刪的結點裡
按順序插入:退化成一條鏈
二叉搜尋樹的形狀由插入順序決定。如果資料本來就是排好序的,每個新數都比前面的大,全都掛在右邊:樹變成一條鏈,查詢退回 O(n),和鏈結串列一樣慢。
1#include <iostream>2#include <algorithm>3using namespace std;4 5struct TreeNode {6 int val;7 TreeNode *left, *right;8 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}9};10 11TreeNode* insert(TreeNode* t, int v) {12 if (t == nullptr) return new TreeNode(v);13 if (v < t->val) t->left = insert(t->left, v);14 else if (v > t->val) t->right = insert(t->right, v);15 return t;16}17 18int height(TreeNode* t) {19 if (!t) return 0;20 return max(height(t->left), height(t->right)) + 1;21}22 23int main() {24 TreeNode *a = nullptr, *b = nullptr;25 unsigned s = 7;26 for (int i = 0; i < 300; i++) {27 s = s * 1103515245 + 12345;28 a = insert(a, s % 100000); // 打亂的 300 個數29 b = insert(b, i); // 0, 1, 2, ……, 29930 }31 cout << "打亂插入:高度 " << height(a) << endl;32 cout << "按順序插入:高度 " << height(b) << endl;33 return 0;34}
打亂插入:高度 17 按順序插入:高度 300
打亂的 300 個數,高度只有 17(log₂ 300 ≈ 8,隨機插入的樹大約高兩倍多);按順序插入,高度就是 300:一條鏈。平衡二元樹(AVL 樹、紅黑樹)就是為了這個問題:插入以後自己轉一轉,保證高度一直是 O(log n)。C++ 的 std::set 和 std::map 裡面就是紅黑樹,這一課最後一關會用到。
| 操作 | 平均(樹勻稱) | 最壞(一條鏈) |
|---|---|---|
| 查詢 | O(log n) | O(n) |
| 插入 | O(log n) | O(n) |
| 刪除 | O(log n) | O(n) |
考試裡: 「按某個順序插入後,畫出二叉搜尋樹」「刪除某個結點後的樹」「查詢某個數比較了幾次」:都按左小右大一步步走。查詢成功的平均查詢長度(ASL)= 每個結點所在的層數加起來,除以結點數。
往空樹裡依次插入下面哪幾個序列,會得到一條鏈(高度是 5)?可以選好幾個。
1 5 2 4 3 是左右來回拐的鏈:5 在 1 的右邊,2 在 5 的左邊,4 在 2 的右邊,3 在 4 的左邊,每層只有一個結點。3 1 4 2 5 的根 3 左右都有孩子,高度只有 3。往空樹裡依次插入 8 3 10 1 6。查詢成功的平均查詢長度(ASL)是多少?
用 STL 寫
std::set<int> 就是一棵存 int 的二叉搜尋樹,std::map<K, V> 是按鍵排的二叉搜尋樹,每個結點多帶一個值。它們裡面是紅黑樹:每次插入、刪除以後自己轉幾下,高度一直不超過 2 log₂ n,所以不管資料怎麼來,都是 O(log n)。用法和這一課自己寫的一一對應:
1#include <iostream>2#include <set>3#include <map>4#include <string>5using namespace std;6 7int main() {8 set<int> s;9 for (int x : {8, 3, 10, 1, 6, 14, 4, 7})10 s.insert(x); // 自己寫的 insert11 s.insert(6); // 已經有了,不放第二次12 for (int x : s) cout << x << ' '; // 從小到大:就是中序遍歷13 cout << "\n個數 " << s.size() << endl;14 15 cout << "有 7 嗎:" << (s.find(7) != s.end() ? "有" : "沒有")16 << ",有 5 嗎:" << (s.count(5) ? "有" : "沒有") << endl;17 s.erase(3); // 自己寫的 erase18 cout << "第一個 >= 5 的:" << *s.lower_bound(5) << endl;19 cout << "第一個 > 8 的:" << *s.upper_bound(8) << endl;20 21 map<string, int> cnt; // 鍵 → 值,也按鍵排好22 for (string w : {"pear", "apple", "fig", "apple", "pear", "apple"})23 cnt[w]++;24 for (auto& kv : cnt)25 cout << kv.first << " " << kv.second << endl;26 return 0;27}
1 3 4 6 7 8 10 14 個數 8 有 7 嗎:有,有 5 嗎:沒有 第一個 >= 5 的:6 第一個 > 8 的:10 apple 3 fig 1 pear 2
lower_bound(5) 走的就是查詢那條路:比 5 小往右,否則記下來再往左,最後記下的是「第一個不小於 5 的」。5 不在樹裡,所以拿到的是 6。map 的 cnt[w] 在鍵不存在時先插一個值為 0 的結點,再 ++。
自己寫的 BST 遇到排好序的資料就變成一條鏈;set 不會。給 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 14struct TreeNode {15 int val;16 TreeNode *left, *right;17 TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}18};19 20TreeNode* insert(TreeNode* t, int v) {21 if (t == nullptr) return new TreeNode(v);22 cmps++;23 if (v < t->val) t->left = insert(t->left, v);24 else if (v > t->val) t->right = insert(t->right, v);25 return t;26}27 28int main() {29 TreeNode* t = nullptr;30 for (int i = 0; i < 300; i++) t = insert(t, i);31 cout << "自己寫的 BST:比較 " << cmps << " 次" << endl;32 33 cmps = 0;34 set<int, CountLess> s;35 for (int i = 0; i < 300; i++) s.insert(i);36 cout << "std::set:比較 " << cmps << " 次" << endl;37 return 0;38}
自己寫的 BST:比較 44850 次 std::set:比較 3937 次
同樣按 0, 1, …, 299 插進去,自己寫的樹每次都要走到鏈的最底下,一共 0 + 1 + … + 299 次;紅黑樹一直是平衡的,每次只走十來層。
| 操作 | set / map | 說明 |
|---|---|---|
insert、find、count、erase | O(log n) | 一條從根往下的路 |
lower_bound、upper_bound | O(log n) | 第一個 ≥ x / 第一個 > x |
| 從頭到尾遍歷 | O(n) | 中序:從小到大 |
begin()、rbegin() | O(1) | 最小的、最大的 |
要放重複的值,用 multiset / multimap。只要「在不在」、不在乎順序時,unordered_set / unordered_map 平均 O(1) 更快;要順序、要範圍(「5 到 10 之間有哪些」)時才用 set / map。
面試裡: 「找比 x 大的最小的數」「滑動窗口裡維護一組有序的數」「區間有沒有重疊」,都是 set 加 lower_bound 的題。注意要用成員函式 s.lower_bound(x),不要寫 std::lower_bound(s.begin(), s.end(), x):後者不知道樹的結構,在 set 上是 O(n)。
set 裡有 1 3 6 8。程式顯示什麼?
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s = {1, 3, 6, 8};7 cout << *s.lower_bound(4) << " " << *s.lower_bound(6) << " " << *s.upper_bound(6) << "\n";8 return 0;9}
lower_bound(x) 是第一個 ≥ x 的:4 不在裡面,第一個不小於 4 的是 6;6 在裡面,拿到的就是 6 自己。upper_bound(6) 是第一個 > 6 的:8。小結
二叉搜尋樹:左小右大,一條路走到底
- 查詢、插入:和當前結點比,小往左、大往右,O(高度);中序遍歷是從小到大
- 刪除兩個孩子的結點:用右子樹最小的(後繼)頂替
- 按順序插入退化成鏈,O(n);平衡樹保證 O(log n)
- set / map 是紅黑樹:insert、find、erase、lower_bound 都是 O(log n)
1TreeNode* insert(TreeNode* t, int v) {2 if (!t) return new TreeNode(v);3 if (v < t->val) t->left = insert(t->left, v);4 else if (v > t->val) t->right = insert(t->right, v);5 return t;6}