美文网首页
226. Invert Binary Tree

226. Invert Binary Tree

作者: larrymusk | 来源:发表于2017-11-20 23:06 被阅读0次

    细节处理题,递归对左右树进行翻转,
    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;
    }

    相关文章

      网友评论

          本文标题:226. Invert Binary Tree

          本文链接:https://www.haomeiwen.com/subject/olobvxtx.html