二元樹的四種遍歷
二元樹遍歷按四種順序訪問每個結點:前序(根左右)、中序(左根右)、後序(左右根),以及用 std::queue 的層序;在表示式樹上,前三種就是字首、中綴、字尾表示式。
陣列從頭走到尾,訪問順序只有一種。樹不一樣:在一個結點上,是先處理自己,還是先去左邊、再去右邊?順序不同,得到的序列完全不同,而考試幾乎每年都會給一棵樹,讓你寫出它的遍歷序列。
前序、中序、後序:只差「自己」放在哪
三種遞迴遍歷都是「先左子樹,再右子樹」,區別只在訪問根的時機:
- 前序(根左右):先訪問自己,再左、再右。
- 中序(左根右):先左,再訪問自己,再右。
- 後序(左右根):先左、再右,最後訪問自己。
中序和後序只是把 cout 那一行挪到兩次遞迴中間或者最後。
1void preorder(TreeNode* t) {2 if (t == nullptr) return;3 cout << t->val << ' '; // 根4 preorder(t->left); // 左5 preorder(t->right); // 右6}
同一棵樹的另外兩種:中序 4 2 5 1 3 6(每個結點都在它左子樹的後面、右子樹的前面),後序 4 5 2 6 3 1(根永遠在最後)。上一課的 destroy 就是一次後序遍歷:兩個孩子都刪完了,才輪到自己。
寫出這棵樹的前序遍歷。
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
寫出這棵樹的後序遍歷。
1 A2 / \3 B C4 \ /5 D E6 /7 F
把兩個空格填好,讓 in 成為中序遍歷:先左、再自己、再右。樹是第一關圖裡那棵,程式要顯示 4 2 5 1 3 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 11void in(TreeNode* t) {12 if (t == nullptr) return;13 ;14 cout << t->val << " ";15 ;16}17 18int main() {19 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),20 new TreeNode(3, nullptr, new TreeNode(6)));21 in(t);22 cout << "\n";23 return 0;24}
cout 夾在兩次遞迴中間,前面去左邊,後面去右邊。兩個空格對調就變成「右根左」,輸出 6 3 1 5 2 4。寫後序遍歷
✓補全 post:左、右、最後印出自己。
1 6 3 14 10 8
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 // 空樹直接返回;否則先左、再右,最後 cout << t->val << ' '13}14 15int main() {16 TreeNode* t = new TreeNode(8, new TreeNode(3, new TreeNode(1), new TreeNode(6)),17 new TreeNode(10, nullptr, new TreeNode(14)));18 post(t);19 cout << endl;20 return 0;21}
表示式樹:三種遍歷就是三種寫法
算式 (3 + 4) * 5 可以存成一棵樹:運算子在內部結點,數字在葉子。對它做三種遍歷,正好得到字首、中綴和字尾表示式,字尾表示式就是第 2 章用堆疊求值的那種。這一節的結點存的是字元,所以 val 是 char。
1#include <iostream>2using namespace std;3 4struct TreeNode {5 char val;6 TreeNode *left, *right;7 TreeNode(char v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void pre(TreeNode* t) {12 if (!t) return;13 cout << t->val << ' ';14 pre(t->left);15 pre(t->right);16}17 18void in(TreeNode* t) {19 if (!t) return;20 in(t->left);21 cout << t->val << ' ';22 in(t->right);23}24 25void post(TreeNode* t) {26 if (!t) return;27 post(t->left);28 post(t->right);29 cout << t->val << ' ';30}31 32int main() {33 // (3 + 4) * 534 TreeNode* t = new TreeNode('*', new TreeNode('+', new TreeNode('3'), new TreeNode('4')),35 new TreeNode('5'));36 cout << "前序:";37 pre(t);38 cout << "\n中序:";39 in(t);40 cout << "\n後序:";41 post(t);42 cout << endl;43 return 0;44}
前序:* + 3 4 5 中序:3 + 4 * 5 後序:3 4 + 5 *
注意中序打印出來是 3 + 4 * 5:括號丟了,按習慣會先算 4 * 5,意思變了。所以中綴表示式要靠括號,而字首和字尾不需要括號也不會有歧義,這就是計算機喜歡字尾表示式的原因。
中序遍歷這棵樹(B 只有左孩子 D),印出什麼?
1#include <iostream>2using namespace std;3 4struct TreeNode {5 char val;6 TreeNode *left, *right;7 TreeNode(char v, TreeNode* l = nullptr, TreeNode* r = nullptr)8 : val(v), left(l), right(r) {}9};10 11void in(TreeNode* t) {12 if (!t) return;13 in(t->left);14 cout << t->val;15 in(t->right);16}17 18int main() {19 // A20 // B C21 // D E F22 TreeNode* t = new TreeNode('A', new TreeNode('B', new TreeNode('D')),23 new TreeNode('C', new TreeNode('E'), new TreeNode('F')));24 in(t);25 cout << endl;26 return 0;27}
這棵表示式樹的後序遍歷(也就是字尾表示式)是什麼?
1 *2 / \3 3 +4 / \5 4 5
* 3 + 4 5 是前序(字首),3 * 4 + 5 是中序,括號丟了以後意思就變成 (3 × 4) + 5。3 4 + 5 * 是 (3 + 4) × 5 那棵樹。字尾表示式 2 3 4 * + 的值是多少?(從左往右讀,數字入堆疊,遇到運算子就彈出兩個數算完再壓回去)
* 彈出 4 和 3,壓回 12;+ 彈出 12 和 2,壓回 14。它對應的表示式樹是根 +、左邊 2、右邊 3 * 4,中綴寫法 2 + 3 × 4。層序:一層一層,用佇列
層序遍歷從根開始一層一層、每層從左往右訪問。它不是遞迴,而是用佇列:根先入隊;每次出隊一個結點,訪問它,再把它的左右孩子(不空的話)入隊。先進來的先處理,所以上一層總是比下一層先出來。先用一個數組和兩個下標自己寫佇列:
head1TreeNode* q[100];2int head = 0, tail = 0;3q[tail++] = t;4while (head < tail) {5 TreeNode* x = q[head++];6 cout << x->val << ' ';7 if (x->left) q[tail++] = x->left;8 if (x->right) q[tail++] = x->right;9}
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 level(TreeNode* t) {12 TreeNode* q[100];13 int head = 0, tail = 0;14 if (t) q[tail++] = t;15 while (head < tail) {16 TreeNode* x = q[head++]; // 出隊17 cout << x->val << ' ';18 if (x->left) q[tail++] = x->left; // 孩子入隊19 if (x->right) q[tail++] = x->right;20 }21 cout << endl;22}23 24void destroy(TreeNode* t) { // 後序:先刪孩子,再刪自己25 if (!t) return;26 destroy(t->left);27 destroy(t->right);28 delete t;29}30 31int main() {32 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),33 new TreeNode(3, nullptr, new TreeNode(6)));34 level(t);35 destroy(t);36 return 0;37}
1 2 3 4 5 6
| 遍歷 | 順序 | 寫法 | 這棵樹的結果 |
|---|---|---|---|
| 前序 | 根 左 右 | 遞迴,先訪問 | 1 2 4 5 3 6 |
| 中序 | 左 根 右 | 遞迴,中間訪問 | 4 2 5 1 3 6 |
| 後序 | 左 右 根 | 遞迴,最後訪問 | 4 5 2 6 3 1 |
| 層序 | 一層一層 | 佇列 | 1 2 3 4 5 6 |
四種都是每個結點訪問一次,O(n)。遞迴的三種額外用的是呼叫堆疊,深度等於樹高;層序用的是佇列,最多同時放一層的結點。
考試裡: 手推前序的快辦法:從根出發,沿著樹的外圍逆時針繞一圈,第一次經過結點時寫下它;中序是從下面經過時寫,後序是最後一次經過時寫。後序遍歷的最後一個、前序遍歷的第一個,一定是根。
寫出這棵樹的層序遍歷。
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
把 while 裡的這四行排好,讓層序遍歷顯示 1 2 3 4 5 6。樹是第一關圖裡那棵。
if (x->right) q[tail++] = x->right;TreeNode* x = q[head++];if (x->left) q[tail++] = x->left;cout << x->val << " ";
1 2 3 4 5 6
x,才能訪問它、把它的孩子入隊;左孩子要比右孩子先入隊,同一層才是從左往右。訪問和入隊誰先都可以:輸出一樣。用這一關的佇列做層序遍歷,樹是 4 層的滿二元樹(15 個結點)。佇列裡最多同時有幾個結點?
每層有幾個結點
✓用 queue 做層序遍歷,按層印出每一層的結點個數。辦法:每一輪開始時,佇列裡正好是一整層,先記下 q.size()。
1 2 3 1
1#include <iostream>2#include <queue>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 widths(TreeNode* root) {13 queue<TreeNode*> q;14 q.push(root);15 while (!q.empty()) {16 int k = q.size(); // 這一層有 k 個17 cout << k << ' ';18 // 把這 k 個都出隊,並把它們的孩子入隊19 }20 cout << endl;21}22 23int main() {24 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),25 new TreeNode(3, nullptr, new TreeNode(6, new TreeNode(7))));26 widths(t);27 return 0;28}
用 STL 寫
層序那一關自己寫的陣列佇列要猜一個大小(100),樹大了就越界。std::queue 自己會長,寫層序時直接用它。前序也能不遞迴:拿 std::stack 代替呼叫堆疊,出堆疊一個就訪問,再把右孩子先放、左孩子後放,左邊就先出來。
1#include <iostream>2#include <queue>3#include <stack>4using namespace std;5 6struct TreeNode {7 int val;8 TreeNode *left, *right;9 TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr)10 : val(v), left(l), right(r) {}11};12 13void level(TreeNode* root) {14 queue<TreeNode*> q;15 if (root) q.push(root);16 while (!q.empty()) {17 TreeNode* x = q.front();18 q.pop();19 cout << x->val << ' ';20 if (x->left) q.push(x->left);21 if (x->right) q.push(x->right);22 }23 cout << endl;24}25 26void preorder(TreeNode* root) {27 stack<TreeNode*> s;28 if (root) s.push(root);29 while (!s.empty()) {30 TreeNode* x = s.top();31 s.pop();32 cout << x->val << ' ';33 if (x->right) s.push(x->right); // 右邊先放34 if (x->left) s.push(x->left); // 左邊後放,先出來35 }36 cout << endl;37}38 39int main() {40 TreeNode* t = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)),41 new TreeNode(3, nullptr, new TreeNode(6)));42 cout << "層序:";43 level(t);44 cout << "前序:";45 preorder(t);46 return 0;47}
層序:1 2 3 4 5 6 前序:1 2 4 5 3 6
queue 和 stack 預設都是套在 deque 外面的一層(deque 是一塊塊的陣列),push、pop、front、top 都是 O(1)。
| 寫法 | 用到的容器 | 額外空間 |
|---|---|---|
| 遞迴前 / 中 / 後序 | 呼叫堆疊 | O(樹高) |
| 不遞迴的前序 | stack<TreeNode*> | O(樹高) |
| 層序 | queue<TreeNode*> | O(最寬那層) |
不遞迴的版本和遞迴的一樣快,好處是深度只受記憶體限制:一條十萬層的鏈,遞迴可能把呼叫堆疊撐破,自己的 stack 不會。
面試裡: 「按層輸出,每層一行」(LeetCode 102)是層序的變形:每一輪開始時先記下 q.size(),正好是這一層的個數。「不用遞迴寫中序」也常被問:一路把左孩子壓堆疊,壓到空了就彈一個、訪問、轉去它的右邊。
不遞迴的前序遍歷裡,為什麼要先把右孩子壓進堆疊,再壓左孩子?
小結
四種遍歷:根在哪,或一層一層
- 前序 根左右,中序 左根右,後序 左右根:只差 cout 放在哪
- 表示式樹:前序 = 字首,中序 = 中綴(要括號),後序 = 字尾
- 層序:queue,出隊一個、孩子入隊;不遞迴的前序:stack,右先入
- 都是 O(n);前序第一個、後序最後一個是根
1void in(TreeNode* t) {2 if (!t) return;3 in(t->left);4 cout << t->val << ' ';5 in(t->right);6}