Sunday, December 7, 2014

Populating Next Right Pointers in Each Node

   /**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */

 void connect(TreeLinkNode *root) {
        TreeLinkNode * leftWall=root;
       
        while(leftWall)
        {
            TreeLinkNode * across=leftWall;
            while(across)
            {
                if(across->left)
                    across->left->next=across->right;
                if(across->right&&across->next)
                    across->right->next=across->next->left;
                across=across->next;   
            }
            leftWall=leftWall->left;
        }
    }

No comments:

Post a Comment