20 lines,concise c++ solution


  • 0
    Z
    void connect(TreeLinkNode *p) {
            while(p){
                TreeLinkNode *nexth=NULL,*nextp=NULL;
                while(p){
                    if(p->left){
                        nexth=nextp=p->left;
                        break;
                    }
                    if(p->right){
                        nexth=nextp=p->right;
                        break;
                    }
                    p=p->next;
                }
                while(p){
                    if(p->left)nextp=nextp->next=p->left;
                    if(p->right)nextp=nextp->next=p->right;
                    p=p->next;
                }
                p=nexth;
                if(nextp)nextp->next=NULL;
            }
        }
    

Log in to reply
 

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