二叉樹遍歷是資料結構核心基本功。本文提供前序、中序、後序(深度優先)與層次(廣度優先)四種遍歷的完整 C++ 實作,對照遞迴與迭代寫法,並解析時間空間複雜度與適用場景。
struct TreeNode {
char val;
TreeNode *left, *right;
TreeNode(char v) : val(v), left(nullptr), right(nullptr) {}
};
| 遍歷順序 | 操作順序 | 典型應用 |
|---|---|---|
| 前序 | 根 → 左 → 右 | 樹的複製、前綴表達式 |
| 中序 | 左 → 根 → 右 | BST 排序輸出、中綴表達式 |
| 後序 | 左 → 右 → 根 | 釋放記憶體、後綴表達式 |
// 前序
void preorder(TreeNode* root) {
if (!root) return;
cout << root->val << ' ';
preorder(root->left);
preorder(root->right);
}
// 中序
void inorder(TreeNode* root) {
if (!root) return;
inorder(root->left);
cout << root->val << ' ';
inorder(root->right);
}
// 後序
void postorder(TreeNode* root) {
if (!root) return;
postorder(root->left);
postorder(root->right);
cout << root->val << ' ';
}
遞迴本質是系統呼叫堆疊,手動模擬可避免棧溢位並便於中斷/恢復。
// 前序迭代:根→左→右,堆疊先壓右再壓左
void preorderIter(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top(); st.pop();
cout << cur->val << ' ';
if (cur->right) st.push(cur->right);
if (cur->left) st.push(cur->left);
}
}
// 中序迭代:左→根→右,沿左鏈入棧
void inorderIter(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur || !st.empty()) {
while (cur) { st.push(cur); cur = cur->left; }
cur = st.top(); st.pop();
cout << cur->val << ' ';
cur = cur->right;
}
}
// 後序迭代:左→右→根,雙棧法或單棧+前驅節點
void postorderIter(TreeNode* root) {
if (!root) return;
stack<TreeNode*> st1, st2;
st1.push(root);
while (!st1.empty()) {
TreeNode* cur = st1.top(); st1.pop();
st2.push(cur);
if (cur->left) st1.push(cur->left);
if (cur->right) st1.push(cur->right);
}
while (!st2.empty()) {
cout << st2.top()->val << ' ';
st2.pop();
}
}
使用佇列,先進先出,逐層訪問。
void levelorder(TreeNode* root) {
if (!root) return;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
cout << cur->val << ' ';
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
| 演算法 | 時間 | 空間(最壞) | 備註 |
|---|---|---|---|
| 遞迴 DFS | O(N) | O(H) ~ O(N) | H=樹高,歪樹退化為 O(N) |
| 迭代 DFS | O(N) | O(H) ~ O(N) | 手動堆疊,可控制記憶體 |
| 層次 BFS | O(N) | O(W) ~ O(N) | W=最大層寬,滿二叉樹最底層 N/2 |
掌握四大遍歷的遞迴與迭代雙重實作,不僅能應對面試考題,更能在實際專案中根據樹的形狀、記憶體限制、處理需求選擇最適合的策略。建議熟練背誦遞迴三式,重點練習迭代中序與後序的堆疊邏輯。