细节处理题,递归对左右树进行翻转,
1,注意穿参,因为需要修改左右指针,需要传递指针的地址
em(&root->left,&root->right);
2,注意对单子树翻转的shh
void em(struct TreeNode **left, struct TreeNode **right)
{
//swap(left->left,right->right) swap(left->right, right->left)
if(*left == NULL && *right == NULL){
}else if(*left != NULL && *right == NULL){
*right = *left;
*left = NULL;
em(&(*right)->left,&(*right)->right);
}
else if(*left == NULL && *right != NULL){
*left = *right;
*right = NULL;
em(&(*left)->left, &(*left)->right);
}
else{
int tmp = (*left)->val;
(*left)->val = (*right)->val;
(*right)->val = tmp;
em(&(*left)->left,&(*right)->right);
em(&(*left)->right, &(*right)->left);
}
}
struct TreeNode* invertTree(struct TreeNode* root) {
if(root == NULL)
return NULL;
em(&root->left,&root->right);
return root;
}
网友评论