Sunday, December 7, 2014

Populating Next Right Pointers in Each Node II

    void connect(TreeLinkNode *root) {
        TreeLinkNode * leftWall=root;
        while(leftWall){
            TreeLinkNode *across=leftWall;
            TreeLinkNode *next=NULL;// the first node of next level
            TreeLinkNode * pre = NULL; // previous node on the same level
          
            while(across){
                if (!next) next = across->left?across->left:across->right;
                if(across->left){
                    if(pre) {pre->next=across->left;}
                    pre=across->left;
                }
                   
                if(across->right){
                    if(pre)   {pre->next=across->right;}
                    pre=across->right;
                }
                across=across->next;
            }
            leftWall=next;
        }
    }

No comments:

Post a Comment