36 ms C++ solution using a subfunction


  • 0
    J
    void connect(TreeLinkNode *root) {
    
        if(root==NULL) return;
        
        TreeLinkNode* pre=root, *cur=findFirst(pre), *head=cur;
        
        while(head){
            if(cur==pre->left){
                if(pre->right) {
                    cur->next=pre->right;
                    cur=cur->next;
                }
            }
            pre=pre->next;
            if(pre){
                cur->next=findFirst(pre);
                cur=cur->next;
                if(cur!=NULL) continue;
            }
                pre=head;
                cur=findFirst(pre);
                head=cur;
            
        }
    }
    
    inline TreeLinkNode* findFirst(TreeLinkNode*& pre){
        while(pre){
            if(pre->left) return pre->left;
            if(pre->right) return pre->right;
            else pre=pre->next;
        }
        return NULL;
    }

Log in to reply
 

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