方法一:递归法
struct TreeNode* invertTree(struct TreeNode* root){
if(root==NULL) return NULL;
else{
struct TreeNode *temp;
invertTree(root->left);
invertTree(root->right);
temp=root->right;
root->right=root->left;
root->left=temp;
}
return root;
}
方法二:用队列实现
struct TreeNode* invertTree(struct TreeNode* root){
struct TreeNode *point[120];
struct TreeNode *temp;
struct TreeNode *head=root;
int left=0;
int right=0;
point[right++]=root;
while(head!=NULL||left<right){
head=point[left++];
if(head!=NULL){
temp=head->left;
head->left=head->right;
head->right=temp;//交换左右子树
if(head->left!=NULL)
point[right++]=head->left;
if(head->right!=NULL)
point[right++]=head->right;//以上两个if负责将左右子树中非空的子树加入队列
head=NULL;
}
}
return root;
}