226. 翻转二叉树
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
- 递归法
前序
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
swap(root->left, root->right);//前序
invertTree(root->left);
invertTree(root->right);
return root;
}
};
后序
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
invertTree(root->left);//左
invertTree(root->right);//右
swap(root->left, root->right);
return root;
}
};
- 迭代法
深度优先
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* temp = st.top();
st.pop();
swap(temp->left, temp->right);
if(temp->right != nullptr) st.push(temp->right);
if(temp->left != nullptr) st.push(temp->left);
}
return root;
}
};
广度优先
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
queue<TreeNode*> que;
if(root != nullptr) que.push(root);
while(!que.empty()){
int n = que.size();
while(n--){
TreeNode* temp = que.front();
que.pop();
swap(temp->left, temp->right);
if(temp->left != nullptr) que.push(temp->left);
if(temp->right != nullptr) que.push(temp->right);
}
}
return root;
}
};