二元樹和遞迴
二元樹每個結點最多兩個孩子,左右各是一棵更小的二元樹,所以樹的程式碼多是遞迴:空樹返回 0,否則合併左右子樹,比如 count(t->left) + count(t->right) + 1。
資料夾裡套資料夾,比賽的對陣表,一個算式 (3 + 4) * 5:都是一個東西下面掛著幾個同樣結構的東西。這種結構叫樹。每個結點最多掛兩個的,叫二元樹,是資料結構課裡最核心的一種。
結點:一個值,兩個指標
和鏈結串列的結點比,二元樹的結點只是把一個 next 換成了 left 和 right。沒有孩子的地方是 nullptr。建構函式給兩個指標預設值,new TreeNode(4) 就是一個葉子。
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};
最上面的結點叫根;沒有孩子的叫葉子;從根往下數,根在第 1 層,一棵樹有幾層就是它的高度。
這就是遞迴的來源:左子樹和右子樹本身也是二元樹,而且比原來的小。所以問一棵樹的任何事,都可以先問它的兩棵子樹,再把答案合起來;子樹是空的(nullptr)就直接給答案。
這棵樹的高度是幾?有幾個葉子?
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
選一個填進空格,讓程式顯示 1 2 1:根是 1,左孩子是 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 11int main() {12 TreeNode* t = TreeNode(1, new TreeNode(2));13 cout << t->val << " " << t->left->val << " " << (t->right == nullptr) << "\n";14 return 0;15}
new 造出來,得到的是一個 TreeNode*,正好交給 t。new TreeNode(1, new TreeNode(2)) 只給了左孩子,右孩子用預設值 nullptr,所以最後印出 1(真)。遞迴算結點數和高度
結點數 = 左子樹的結點數 + 右子樹的結點數 + 1(自己)。高度 = 左右子樹裡高的那個 + 1。空樹的結點數和高度都是 0。
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 count(TreeNode* t) {13 if (t == nullptr) return 0;14 return count(t->left) + count(t->right) + 1;15}16 17int height(TreeNode* t) {18 if (t == nullptr) return 0;19 int l = height(t->left);20 int r = height(t->right);21 return max(l, r) + 1;22}23 24void destroy(TreeNode* t) { // 先刪兩個孩子,再刪自己25 if (t == nullptr) return;26 destroy(t->left);27 destroy(t->right);28 delete t;29}30 31int main() {32 // 第一關圖裡的那棵樹:1 下面是 2、3,2 下面是 4、5,3 的右孩子是 633 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),34 new TreeNode(3, nullptr, new TreeNode(6)));35 cout << "結點數 " << count(t) << ",高度 " << height(t) << endl;36 destroy(t);37 return 0;38}
結點數 6,高度 3
每個結點都是 new 出來的,用完要 delete。destroy 也是一個遞迴:先把兩棵子樹刪乾淨,最後刪自己;反過來先刪自己,就再也拿不到 t->left 了。後面的例子為了短,有時省掉這一步,真寫程式時別省。
點「視覺化」可以看到 count 的呼叫在堆疊裡一層層疊起來:每到一個結點就再往下問兩次,問到 nullptr 才開始返回。
1int height(TreeNode* t) {2 if (t == nullptr) return 0;3 int l = height(t->left);4 int r = height(t->right);5 return max(l, r) + 1;6}
所有「問遍整棵樹」的遞迴都是這個樣子:每個結點訪問一次,O(n);遞迴的深度等於樹的高度,最壞(樹長成一條鏈)是 O(n)。
這棵樹和第一關圖裡的一樣:根是 1,葉子是 4、5、6。f 算的是什麼,印出幾?
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 f(TreeNode* t) {12 if (t == nullptr) return 0;13 if (t->left == nullptr && t->right == nullptr) return t->val;14 return f(t->left) + f(t->right);15}16 17int main() {18 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),19 new TreeNode(3, nullptr, new TreeNode(6)));20 cout << f(t) << endl;21 return 0;22}
這個 count 把空樹算錯了,顯示的是 13,不是 6。只改綠框裡的數,讓它數對。
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 count(TreeNode* t) {12 if (t == nullptr) return ;13 return count(t->left) + count(t->right) + 1;14}15 16int main() {17 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),18 new TreeNode(3, nullptr, new TreeNode(6)));19 cout << count(t) << "\n";20 return 0;21}
6
把 height 的這三行排好:先處理空樹,再問兩棵子樹,最後算自己。樹是第一關那棵,程式要顯示 3。
return max(l, r) + 1;int l = height(t->left), r = height(t->right);if (t == nullptr) return 0;
3
t 是 nullptr 時去讀 t->left,程式就停下報錯。問完兩棵子樹,才能用它們的答案算自己。height 遞迴的時候,呼叫堆疊裡最多同時疊著幾層呼叫,由什麼決定?
數葉子
✓補全 leaves,返回葉子的個數。
4
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 leaves(TreeNode* t) {12 // 空樹:0;葉子:1;否則左右加起來13 return 0;14}15 16int main() {17 TreeNode* t = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6, new TreeNode(4), new TreeNode(7))),18 new TreeNode(10, nullptr, new TreeNode(14)));19 cout << leaves(t) << endl;20 return 0;21}
最大的值
✓補全 max_val:返回整棵樹裡最大的值(樹不是空的)。
20
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 max_val(TreeNode* t) {13 // 先當自己最大;左子樹、右子樹不空的話,各問一次,比一比14 return t->val;15}16 17int main() {18 TreeNode* t = new TreeNode(5, new TreeNode(12, new TreeNode(3)),19 new TreeNode(7, new TreeNode(20), new TreeNode(1)));20 cout << max_val(t) << endl;21 return 0;22}
考試常用的幾條性質
| 名稱 | 是什麼 | 結點數 |
|---|---|---|
| 滿二元樹 | 每一層都排滿 | 高度 h 時正好 2ʰ − 1 個 |
| 完全二元樹 | 除了最後一層都排滿,最後一層從左往右連續排 | n 個結點時高度是 ⌊log₂ n⌋ + 1 |
還有一條几乎每年都考:葉子數 n₀ = 有兩個孩子的結點數 n₂ + 1。拿第一關那棵樹數一數:有兩個孩子的是 1 和 2(n₂ = 2),葉子是 4、5、6(n₀ = 3),正好多 1。
為什麼:除了根,每個結點頭上都有一條邊,所以邊數 = n − 1;而邊數也等於 n₁ + 2n₂(每個有一個孩子的結點出一條,有兩個孩子的出兩條)。n = n₀ + n₁ + n₂ 代進去,就得到 n₀ = n₂ + 1。
考試裡: 「一棵二元樹有 10 個葉子,度為 2 的結點有幾個」:9 個。「完全二元樹有 1000 個結點,高度是多少」:⌊log₂ 1000⌋ + 1 = 10。完全二元樹也是這一章後面要講的「堆」的形狀。
一棵二元樹有 15 個葉子,還有 10 個只有一個孩子的結點。它一共有幾個結點?
一棵完全二元樹有 100 個結點,它的高度是幾?
高度為 5 的滿二元樹有幾個結點、幾個葉子?
用 STL 寫
STL 沒有「二元樹」這個容器:TreeNode 這樣的結構總是自己寫。但好幾個容器裡面其實就是樹,只是不讓你直接碰結點:
| 容器 | 裡面是什麼樹 | 主要操作的代價 |
|---|---|---|
set / map / multiset / multimap | 紅黑樹(一種自己保持平衡的二叉搜尋樹) | 插入、查詢、刪除 O(log n) |
priority_queue | 完全二元樹(堆),按層存在一個 vector 裡 | push / pop O(log n),top O(1) |
完全二元樹一層層排滿,沒有空位,所以根本不用指標:按層把值放進 vector,下標 i 的左孩子是 2i + 1,右孩子是 2i + 2,父親是 (i − 1) / 2。
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6// 完全二元樹按層存進 vector:下標 i 的孩子是 2i+1 和 2i+27int height(const vector<int>& a, int i) {8 if (i >= (int)a.size()) return 0;9 return max(height(a, 2 * i + 1), height(a, 2 * i + 2)) + 1;10}11 12int main() {13 vector<int> a = {1, 2, 3, 4, 5, 6};14 int n = a.size();15 for (int i = 0; i < n; i++) {16 if (2 * i + 1 >= n) break; // 後面的都是葉子17 cout << a[i] << " 的孩子:" << a[2 * i + 1];18 if (2 * i + 2 < n) cout << " " << a[2 * i + 2];19 cout << endl;20 }21 cout << "高度 " << height(a, 0) << endl;22 return 0;23}
1 的孩子:2 3 2 的孩子:4 5 3 的孩子:6 高度 3
注意這棵樹和第一關那棵不一樣:按層排滿時,6 是 3 的左孩子。像第一關那樣「3 只有右孩子」的樹,存進陣列就得給空位留格子,一條斜的鏈要 2ⁿ 個格子,所以一般的樹還是用指標。這一章後面的堆就是用這個 vector 寫的。
面試裡: LeetCode 給的 TreeNode 和這一課的幾乎一樣(多一個無參建構函式),函式拿到的是根指標 TreeNode* root,空樹就是 nullptr。先寫「空樹返回什麼」,再寫「左右的答案怎麼合起來」,大部分樹題就寫完了一半。
完全二元樹按層存進 vector,下標 i 的孩子是 2i + 1 和 2i + 2。下標 4 的父親是下標幾?
小結
二元樹:左右各是一棵更小的樹
- 結點:val + left + right,沒有孩子的地方是 nullptr;new 出來的要 delete
- 樹的問題都先問左右子樹,再合起來;空樹直接給答案
- 每個結點訪問一次 O(n),遞迴深度 = 高度
- n₀ = n₂ + 1;滿二元樹 2ʰ − 1 個結點;完全二元樹可以存進 vector
1int count(TreeNode* t) {2 if (t == nullptr) return 0;3 return count(t->left) + count(t->right) + 1;4}