class Solution {//递归
public:
TreeNode* invertTree(TreeNode* root) {
if(root!=NULL){
TreeNode *temp=root->left;
root->left=root->right;
root->right=temp;
if(root->left) invertTree(root->left);
if(root->right) invertTree(root->right);
}
return root;
}
};
class Solution {//前序遍历迭代
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return root;
stack<TreeNode*> 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;
}
};
class Solution {//层次遍历迭代
public:
TreeNode* invertTree(TreeNode* root) {
if(root==NULL) return root;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
TreeNode *cur=q.front();
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
swap(cur->left,cur->right);
}
return root;
}
};