二叉樹看起來唬人,其實結構比單鏈表只多了一點點東西。先把兩者的結點定義擺在一起對比:
/* 單鏈表結點 */
struct SingleList {
int element;
struct SingleList *next;
};
/* 二叉樹結點 */
struct BinaryTree {
int element;
struct BinaryTree *left;
struct BinaryTree *right;
};
差別一目了然:單鏈表只有一個 next 指針,二叉樹有 left 與 right 兩個。也就是說,單鏈表每個結點只有一個孩子,二叉樹每個結點有兩個孩子(其中一個可以是 NULL)。理解了這點,二叉樹演算法的本質差異也就清楚了:每訪問完一個結點,接下來要處理的是兩個子樹,而鏈表只需往前走一步。
由此衍生出兩大流派:廣度優先遍歷(BFS)與深度優先遍歷(DFS)。
對單鏈表而言,BFS 和 DFS 完全等價,因為每個結點只有唯一的下一步。二叉樹則不然:每個結點有兩個孩子,你可以先沿著孩子一路走到底(DFS),也可以先把同層的兄弟結點走完(BFS)。
實現上,DFS 依賴棧結構(多數人直接用遞歸,等價於系統幫你維護了棧),BFS 依賴隊列。
void dfs(BinaryTree *root) {
if (NULL == root) return;
dfs(root->left);
dfs(root->right);
}
void bfs(BinaryTree *root) {
if (NULL == root) return;
queue<BinaryTree *> que;
que.push(root);
while (!que.empty()) {
BinaryTree *pNode = que.front();
que.pop();
if (pNode->left) que.push(pNode->left);
if (pNode->right) que.push(pNode->right);
}
}
多數二叉樹題目兩種方式都能解,但凡涉及「根到葉的路徑」這類問題,DFS 會自然得多——因為路徑本身就是一條深度方向上的鏈。
給定一棵二叉樹與目標值 Sum,找出所有「根到葉」路徑和等於 Sum 的路徑。
思路:用 DFS 一路向下,每訪問一個結點就把它 push 進當前路徑容器 vec,同時把 sum 減去該結點的值再傳給孩子。當某個結點左右孩子皆為 NULL 且此時 sum 恰好等於它的值,說明抵達葉子且路徑成立,把 vec 拷貝進結果集。關鍵細節在回溯:每個結點有兩個孩子,往左走到底再往右走時,路徑必須退回上一層,所以返回前要把剛加入的結點 pop 掉。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int>> res;
vector<int> vec;
void _pathSum(TreeNode* root, int sum) {
if (root == NULL) return;
vec.push_back(root->val);
if (root->left == NULL && root->right == NULL && sum == root->val) {
res.push_back(vec);
return;
}
_pathSum(root->left, sum - root->val);
if (root->left) vec.pop_back();
_pathSum(root->right, sum - root->val);
if (root->right) vec.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if (NULL == root) return res;
_pathSum(root, sum);
return res;
}
};
把這棵樹
4 / \ 2 7 / \ / \ 1 3 6 9
變成
4 / \ 7 2 / \ / \ 9 6 3 1
思路:本質就是遍歷每個結點並交換它的左右孩子,DFS、BFS 皆可。下面用 BFS 示範:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (NULL == root) return NULL;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
TreeNode* pChild = que.front();
que.pop();
TreeNode* tmp = pChild->left;
pChild->left = pChild->right;
pChild->right = tmp;
if (pChild->left) que.push(pChild->left);
if (pChild->right) que.push(pChild->right);
}
return root;
}
};
把 DFS 與 BFS 這兩套骨架吃透,LeetCode 上的二叉樹題目基本都能變形套用。遇到卡住的題,拿紙筆把樹畫出來走一遍,往往比盯著代碼看半小時更有用。