One while loop solution


  • 0
    L

    Uses only one while loop as compared to other solutions:

        void connect(TreeLinkNode *root) {
            if(!root)return;
            TreeLinkNode*curLevel=root,*nextLevel=root->left,
                *nextLevelPrev=NULL, *nextLevelNext=nextLevel;
            root->next=NULL;
            while(true){
                if (nextLevelNext){
                    if(nextLevelPrev)
                        nextLevelPrev->next=nextLevelNext;
                    nextLevelPrev=nextLevelNext;
                    if(!nextLevel)
                        nextLevel=nextLevelNext;
                }
                if(nextLevelNext==curLevel->right){
                    curLevel=curLevel->next;
                    if(curLevel){
                        nextLevelNext=curLevel->left;
                    }
                    else if (nextLevel){
                        nextLevelPrev->next=NULL;
                        curLevel=nextLevel;
                        nextLevelPrev=NULL;
                        nextLevel=nextLevelNext= curLevel->left;
                    }
                    else break;
                }
                else{
                    nextLevelNext=curLevel->right;
                }
            }
        }

Log in to reply
 

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