我的解题:
1.递归
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return nullptr;
swap(root->right,root->left);
mirrorTree(root->right);
mirrorTree(root->left);
return root;
}
};
2.实际这道题就是遍历二叉树
我用了比较好记住的层次遍历,注意判断结点是否是NULL
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(!root) return nullptr;
queue<TreeNode*> q;
q.push(root);
TreeNode* tmp;
while(!q.empty()){
tmp=q.front();
q.pop();
if(tmp==NULL) continue;
swap(tmp->left,tmp->right);
q.push(tmp->right);
q.push(tmp->left);
}
return root;
}
};