給定二叉樹根節點,交換每個節點的左右子樹,返回翻轉後的根節點。原地修改即可。
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
後序遍歷思想:先翻轉子樹,再交換左右指針。時間 O(n),空間 O(h)(遞歸棧)。
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
queue q; q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
swap(cur->left, cur->right);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
return root;
}
空間 O(w)(最大層寬),最壞 O(n)。
TreeNode* invertTree(TreeNode* root) {
if (!root) return nullptr;
stack st; st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top(); st.pop();
swap(cur->left, cur->right);
if (cur->left) st.push(cur->left);
if (cur->right) st.push(cur->right);
}
return root;
}
前序遍歷順序,空間 O(h)。
利用線索二叉樹思想,無棧無遞歸。代碼較長,適合極端空間受限場景。
| 方法 | 時間 | 空間 | 代碼長度 | 推薦場景 |
|---|---|---|---|---|
| 遞歸 | O(n) | O(h) | 極短 | 面試、一般情況 |
| BFS | O(n) | O(w) | 短 | 樹較平衡、需層序邏輯 |
| DFS(棧) | O(n) | O(h) | 短 | 樹較深、避免棧溢出 |
| Morris | O(n) | O(1) | 長 | 嵌入式、巨大樹 |
LeetCode 實測:遞歸 4ms,BFS/DFS 0ms(常數因子差異)。