4/18/2014

Leetcode -- 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) {}  
  * };  
  */  
 class Solution {  
 public:  
   void connect(TreeLinkNode *root) {  
     if(root == NULL) {  
       return;  
     }  
     queue<TreeLinkNode *> q;  
     q.push(root);  
     while(!q.empty()) {  
       queue<TreeLinkNode *> temp;  
       while(!q.empty()) {  
         TreeLinkNode * curr = q.front();  
         q.pop();  
         if(curr->left != NULL) {  
           temp.push(curr->left);  
         }  
         if(curr->right != NULL) {  
           temp.push(curr->right);  
         }  
         if(!q.empty()) {  
           curr->next = q.front();  
         }  
       }  
       std::swap(temp, q);  
     }  
   }  
 };  

No comments: