方法一:递归
翻转左子树给右子树,翻转右子树给左子树。
/**
* 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(!root)
return NULL;
TreeNode* left=invertTree(root->left);
TreeNode* right=invertTree(root->right);
root->left=right;
root->right=left;
return root;
}
};
方法二:迭代
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root)
return NULL;
queue<TreeNode*> q;
q.push(root);
while(q.size()){
TreeNode* cur=q.front();
q.pop();
TreeNode* tmp=cur->left;
cur->left=cur->right;
cur->right=tmp;
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
return root;
}
};