題型與套路:樹
這一課複習二元樹的題:幾乎都是同一個模板,先定空樹返回什麼,再把左右兩個答案合起來;還講每種遍歷適合做什麼,以及考試用的公式。
樹的題看起來五花八門,求深度、判對稱、找路徑、翻轉、找祖先……但面試和考試裡絕大多數都是同一個模板;剩下的是遍歷順序的選擇和幾個計算公式。這一課分五關:四個套路,再加上 STL 在樹題裡怎麼用。程式碼裡的結點都是這一章用的那個:
1struct TreeNode {2 int val;3 TreeNode *left, *right;4 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)5 : val(v), left(l), right(r) {}6};
套路一:問左右,合起來
寫樹的遞迴只要想清楚兩件事:
- 空樹返回什麼(遞迴到底的答案);
- 拿到左右子樹的答案以後,怎麼合成自己的答案。
| 要算的 | 空樹返回 | 怎麼合起來 |
|---|---|---|
| 結點數 | 0 | 左 + 右 + 1 |
| 高度 | 0 | max(左, 右) + 1 |
| 葉子數 | 0 | 是葉子返回 1,否則 左 + 右 |
| 所有值的和 | 0 | 左 + 右 + 自己 |
| 有沒有值為 x 的結點 | false | 自己是 x,或 左有,或 右有 |
| 兩棵樹一樣嗎 | 都空才一樣 | 根一樣,且左左一樣、右右一樣 |
還有一種是往下傳:引數帶著「從根到這裡」的資訊往下走,比如路徑上還差多少、允許的取值範圍(判斷二叉搜尋樹時的 lo、hi)。合起來的是後序的想法,往下傳的是前序的想法,很多題兩樣都用。
注意只有到了葉子才判斷。5 → 4 的和是 9,但 4 不是葉子,所以 9 不算。
用模板求高度:空樹是 0;拿到左右子樹的高度 l 和 r 以後,自己的高度是多少?這棵樹是 1(左孩子 2、右孩子 3),2 只有右孩子 4,3 只有左孩子 5。
1#include <iostream>2#include <algorithm>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 12int height(TreeNode* t) {13 if (!t) return 0;14 int l = height(t->left), r = height(t->right);15 return ;16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, nullptr, new TreeNode(4)), new TreeNode(3, new TreeNode(5)));20 cout << height(t) << "\n";21 return 0;22}
l + r + 1 算的是結點數(5);不加 1,葉子的高度就成了 0,一路往上全是 0。翻轉二元樹
✓補全 invert:先翻轉兩棵子樹,再交換左右指標。翻完中序遍歷應該是從大到小。
9 7 6 4 3 2 1
1#include <iostream>2#include <utility>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 12void invert(TreeNode* t) {13 // 空樹返回;翻左、翻右;交換 t->left 和 t->right14}15 16void in(TreeNode* t) {17 if (!t) return;18 in(t->left);19 cout << t->val << " ";20 in(t->right);21}22 23int main() {24 TreeNode* t = new TreeNode(4, new TreeNode(2, new TreeNode(1), new TreeNode(3)),25 new TreeNode(7, new TreeNode(6), new TreeNode(9)));26 invert(t);27 in(t);28 cout << "\n";29 return 0;30}
路徑和
✓有沒有一條從根到葉子的路,路上的值加起來正好是 sum?往下傳「還差多少」:到了葉子,看還差的是不是正好等於它自己。
1 1 0
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11bool has_sum(TreeNode* t, int sum) {12 // 空樹:false;葉子:sum == t->val;否則去左右找 sum - t->val13 return false;14}15 16int main() {17 // 518 // 4 819 // 11 13 420 // 7 2 121 TreeNode* t = new TreeNode(5,22 new TreeNode(4, new TreeNode(11, new TreeNode(7), new TreeNode(2))),23 new TreeNode(8, new TreeNode(13), new TreeNode(4, nullptr, new TreeNode(1))));24 cout << has_sum(t, 22) << " " << has_sum(t, 26) << " " << has_sum(t, 9) << "\n";25 return 0;26}
套路二:選對遍歷順序
| 遍歷 | 適合做什麼 | 例子 |
|---|---|---|
| 前序 | 先處理自己,再交給孩子:往下傳資訊、複製一棵樹 | 印出目錄結構、路徑和 |
| 中序 | 二叉搜尋樹裡按從小到大 | 第 k 小、判斷是不是二叉搜尋樹 |
| 後序 | 要等孩子的答案:高度、刪除和釋放 | 釋放整棵樹、運算元樹大小 |
| 層序 | 按層、離根最近 | 每層的最大值、最小深度 |
釋放整棵樹一定要用後序:先 delete 兩個孩子,最後 delete 自己。如果先 delete t 再去讀 t->left,讀的就是已經還回去的記憶體(第 1 章講過的懸空指標)。一棵樹的解構函式就是這麼寫的。
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11int freed = 0;12 13void free_tree(TreeNode* t) {14 if (!t) return;15 free_tree(t->left); // 先孩子16 free_tree(t->right);17 cout << "釋放 " << t->val << "\n";18 delete t; // 最後自己:後序19 freed++;20}21 22int main() {23 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4)), new TreeNode(3));24 free_tree(t);25 t = nullptr; // 指標本身還在,指的東西沒了:置空,免得再用26 cout << "一共釋放 " << freed << " 個\n";27 return 0;28}
釋放 4 釋放 2 釋放 3 釋放 1 一共釋放 4 個
要找二叉搜尋樹裡第 3 小的數,用哪種遍歷最順手?
套路三:408 計算題的公式
| 題目問 | 公式 |
|---|---|
| 葉子數和度為 2 的結點數 | n₀ = n₂ + 1 |
| 高度為 h 的二元樹最多幾個結點 | 2ʰ − 1 |
| n 個結點的完全二元樹的高度 | ⌊log₂ n⌋ + 1 |
| n 個結點的完全二元樹有幾個葉子 | ⌈n / 2⌉ |
| 完全二元樹(從 1 編號)結點 i 的孩子、父親 | 2i、2i + 1;⌊i / 2⌋ |
| n 個葉子的哈夫曼樹一共幾個結點 | 2n − 1 |
| n 個結點能組成幾種不同形狀的二元樹 | 卡特蘭數 C(2n, n) / (n + 1),n = 3 時是 5 |
一棵二元樹有 6 個度為 2 的結點,它有幾個葉子?
100 個結點的完全二元樹,高度是幾?
套路四:二叉搜尋樹,比一比再走
二叉搜尋樹多了一個條件:左子樹都比根小,右子樹都比根大。所以很多題不用兩邊都去:和當前結點比一比,答案只可能在一邊,一路往下走一條路就夠,時間是 O(h)(h 是樹高),不是 O(n)。查詢、插入、找最小(一直往左)、找最大(一直往右)都是這個樣子:
1while (t) {2 if (x < t->val) t = t->left; // 只可能在左邊3 else if (x > t->val) t = t->right; // 只可能在右邊4 else return t; // 就是它5}
最近公共祖先也一樣:p、q 都比當前結點小就往左,都比它大就往右;一個在左、一個在右(或者其中一個就是它)時,兩個值就是在這裡分開的,當前結點就是答案。
在這一關的樹裡(依次插入 6 2 8 0 4 7 9 3 5),7 和 9 的最近公共祖先是幾?
二叉搜尋樹的最近公共祖先
✓兩個值 p、q 的最近公共祖先,是從根往下走時第一個把它們分到兩邊(或者就是其中一個)的結點。兩個都比當前小就往左,都比當前大就往右,否則就是它。
6 4 2
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11TreeNode* insert(TreeNode* t, int v) {12 if (!t) 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 lca(TreeNode* t, int p, int q) {19 // 迴圈:p、q 都 < t->val 往左;都 > 往右;否則返回 t->val20 return t->val;21}22 23int main() {24 TreeNode* t = nullptr;25 for (int x : {6, 2, 8, 0, 4, 7, 9, 3, 5})26 t = insert(t, x);27 cout << lca(t, 2, 8) << " " << lca(t, 3, 5) << " " << lca(t, 2, 4) << "\n";28 return 0;29}
用 STL 寫
樹本身 STL 不給你(set / map 裡面的紅黑樹不讓你碰結點),樹題裡寫的還是自己的 TreeNode。STL 用在旁邊:
| 要做的 | 用什麼 | 為什麼 |
|---|---|---|
| 層序、按層統計、最小深度 | queue<TreeNode*> | 先進先出,一層一層出來 |
| 不用遞迴的前序、中序 | stack<TreeNode*> | 自己模擬呼叫堆疊,樹很深也不會堆疊溢位 |
| 由前序、中序重建 | unordered_map<int, int> 存中序裡每個值的下標 | 找根的位置從 O(n) 變成 O(1),整體 O(n) |
| 只要有序地查、插、刪 | set / map | 自己寫的二叉搜尋樹會變斜,紅黑樹保證 O(log n) |
| 第 k 大、合併最小的兩個 | priority_queue | 堆,O(log n) 一次 |
層序最常考的寫法:每一輪先記下佇列裡有幾個,正好就是這一層的結點數。
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5using namespace std;6 7struct TreeNode {8 int val;9 TreeNode *left, *right;10 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)11 : val(v), left(l), right(r) {}12};13 14int main() {15 TreeNode* root = new TreeNode(1, new TreeNode(3, new TreeNode(5), new TreeNode(3)),16 new TreeNode(2, nullptr, new TreeNode(9)));17 queue<TreeNode*> q;18 q.push(root);19 int level = 1;20 vector<TreeNode*> all; // 記下所有結點,最後一起 delete21 while (!q.empty()) {22 int n = q.size(), best = q.front()->val; // 這一層有 n 個23 for (int i = 0; i < n; i++) {24 TreeNode* t = q.front(); q.pop();25 all.push_back(t);26 best = max(best, t->val);27 if (t->left) q.push(t->left);28 if (t->right) q.push(t->right);29 }30 cout << "第 " << level++ << " 層最大:" << best << "\n";31 }32 for (TreeNode* t : all) delete t;33 return 0;34}
第 1 層最大:1 第 2 層最大:3 第 3 層最大:9
面試裡: 樹題先說清楚是哪個套路:「後序合起來」「前序往下傳」還是「層序用佇列」,再寫程式碼,面試官通常就放心了。遞迴寫完常被追問「樹退化成鏈、深度 10 萬怎麼辦」:答換成 stack 的迭代寫法。要釋放就說後序,或者像上面這樣把結點收起來一起 delete。
層序按層統計時,每一輪先寫 int n = q.size();,再出隊 n 個。如果直接寫 for (int i = 0; i < (int)q.size(); i++),會怎樣?
q.size() 是此刻佇列裡有幾個。迴圈裡每出隊一個,又可能放進兩個孩子,條件每一輪都在變:一層還沒走完,下一層的結點就被算進來了。先把這一層的個數存進 n,迴圈只走 n 次,正好是一整層。小結
樹的三個套路
- 遞迴模板:空樹返回什麼 + 左右答案怎麼合起來;或者把資訊往下傳
- 中序 = 二叉搜尋樹從小到大;後序 = 等孩子(高度、delete);層序 = queue
- 公式:n₀ = n₂ + 1,2ʰ − 1,⌊log₂ n⌋ + 1,哈夫曼 2n − 1
- 釋放樹用後序,先孩子後自己
1int f(TreeNode* t) {2 if (!t) return 空樹的答案;3 int l = f(t->left), r = f(t->right);4 return 用 l、r 和 t->val 合起來;5}
第 4 章快刷
5 道題:遍歷、由遍歷重建、二叉搜尋樹的形狀、set 的查詢、堆和哈夫曼。先自己算出印出什麼,再點選項。
1 的左孩子是 2(2 只有右孩子 4),右孩子是 3(3 只有左孩子 5)。後序遍歷印出什麼?
1#include <iostream>2using namespace std;3 4struct TreeNode {5 int val;6 TreeNode *left, *right;7 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void post(TreeNode* t) {12 if (!t) return;13 post(t->left);14 post(t->right);15 cout << t->val << " ";16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, nullptr, new TreeNode(4)),20 new TreeNode(3, new TreeNode(5)));21 post(t);22 cout << "\n";23 return 0;24}
前序 1 2 4 5 3 6、中序 4 2 5 1 3 6,重建出來的樹後序印出什麼?
1#include <iostream>2#include <vector>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 12vector<int> pre = {1, 2, 4, 5, 3, 6}, in = {4, 2, 5, 1, 3, 6};13 14// pre[p] 是根;它在中序 in[lo..hi] 裡的位置把左右分開15TreeNode* build(int p, int lo, int hi) {16 if (lo > hi) return nullptr;17 int m = lo;18 while (in[m] != pre[p]) m++;19 int leftSize = m - lo;20 return new TreeNode(pre[p], build(p + 1, lo, m - 1),21 build(p + 1 + leftSize, m + 1, hi));22}23 24void post(TreeNode* t) {25 if (!t) return;26 post(t->left);27 post(t->right);28 cout << t->val << " ";29}30 31int main() {32 post(build(0, 0, 5));33 cout << "\n";34 return 0;35}
依次插入 10 9 8 20 30 40 7,二叉搜尋樹的高度是幾?
1#include <iostream>2#include <algorithm>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 12TreeNode* insert(TreeNode* t, int v) {13 if (!t) return new TreeNode(v);14 if (v < t->val) t->left = insert(t->left, v);15 else if (v > t->val) t->right = insert(t->right, v);16 return t;17}18 19int height(TreeNode* t) {20 if (!t) return 0;21 return max(height(t->left), height(t->right)) + 1;22}23 24int main() {25 TreeNode* t = nullptr;26 for (int x : {10, 9, 8, 20, 30, 40, 7})27 t = insert(t, x);28 cout << height(t) << "\n";29 return 0;30}
set 裡依次放 5 1 4 1 3,印出什麼?
1#include <iostream>2#include <set>3using namespace std;4 5int main() {6 set<int> s;7 for (int x : {5, 1, 4, 1, 3})8 s.insert(x);9 cout << s.size() << " " << *s.begin() << " "10 << *s.lower_bound(2) << " " << *s.upper_bound(4) << "\n";11 return 0;12}
權值 7、2、5、3 的哈夫曼樹:最後堆裡剩的數和 WPL 是多少?
1#include <iostream>2#include <vector>3#include <queue>4#include <functional>5using namespace std;6 7int main() {8 priority_queue<int, vector<int>, greater<int>> q;9 for (int x : {7, 2, 5, 3})10 q.push(x);11 int wpl = 0;12 while (q.size() > 1) {13 int a = q.top(); q.pop();14 int b = q.top(); q.pop();15 wpl += a + b;16 q.push(a + b);17 }18 cout << q.top() << " " << wpl << "\n";19 return 0;20}