Monday, November 25, 2013

LeetCode Problem : Populating Next Right Pointers in Each Node II

Problem


Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

You may only use constant extra space.
For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7
After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL

Code

void connect(TreeLinkNode *root) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(!root)
    return;
    TreeLinkNode *firstChild = root->right;
    if(root->left)
        firstChild = root->left;
    TreeLinkNode *parent = root;
    TreeLinkNode *fc = 0,*sc = 0;
    while(parent){
        TreeLinkNode *tmp = sc;
        if(!parent->left && !parent->right){
            if(tmp)
            tmp->next = 0;
        }
        else if(parent->left && parent->right){
            parent->left->next = parent->right;
            sc = parent->right;
            fc = parent->left;
            if(tmp)
            tmp->next = parent->left;
        }
        else if(parent->left){
            sc = parent->left;
            fc = parent->left;
            if(tmp)
            tmp->next = parent->left;
        }
        else if(parent->right){
            sc = parent->right;
            fc = parent->right;
            if(tmp)
            tmp->next = parent->right;
        }
        if(!firstChild)
            firstChild = fc;
        parent = parent->next;
    }
    connect(firstChild);
}


No comments:

Post a Comment