36ms easy understand O(n) time O(1) space solution


  • -1
    C
    void connect(TreeLinkNode *root) {
        while(root){
            TreeLinkNode *child = NULL, *elderbrother = NULL, *littlebrother = NULL;
            
            if(root->left) littlebrother = root->left,elderbrother = root->left;
            else if(root->right) littlebrother = root->right;
            if(root->right) elderbrother = root->right;
            if(root->left && root->right)
                root->left->next = root->right;
            if(!child) child = littlebrother;
            
            while(root->next){
                TreeLinkNode *elderbrothertmp = NULL, *littlebrothertmp = NULL;
                
                if(root->next->left) littlebrothertmp = root->next->left,elderbrothertmp = root->next->left;
                else if(root->next->right) littlebrothertmp = root->next->right;
                if(root->next->right) elderbrothertmp = root->next->right;
                if(root->next->left && root->next->right)
                    root->next->left->next = root->next->right;
                if(!child) child = littlebrothertmp;
                
                if(elderbrother && littlebrothertmp)
                    elderbrother->next = littlebrothertmp;
                if(elderbrothertmp)
                    elderbrother = elderbrothertmp;
                    
                root = root->next;
            }
            root = child;
        }
    }

  • 0

    In your opinion, this is easy to understand? With no comments, no less?


  • 0
    S
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.