Monday, December 30, 2013

[LeetCode] Populating Next Right Pointers in Each Node II

Populating Next Right Pointers in Each Node II

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



Analysis:
At first glance, I will use a queue to do a BSD. But it requires no extra space other than constant space.
Because there is a next pointer in each node, it is naturally a linked list! We don't need a queue! We just need a pointer to the head node so that the BSD traversal at the next level is possible. And this is only constant space.

Code says!

 /**  
  * 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) {}  
  * };  
  */  
 class Solution {  
 public:  
   void connect(TreeLinkNode *root) {  
     if(root==NULL)  
       return;  
     TreeLinkNode* parent = root;  
     TreeLinkNode* child;  
     while(parent!=NULL)  
     {  
       TreeLinkNode next_head(-1);  
       child = &next_head;  
       while(parent!=NULL)  
       {  
         if(parent->left)  
         {  
           child->next = parent->left;  
           child = child->next;  
         }  
         if(parent->right)  
         {  
           child->next = parent->right;  
           child = child->next;  
         }  
         parent = parent->next;  
       }  
       parent = next_head.next;  
     }  
   }  
 };  

No comments:

Post a Comment