What we are doing here is the following.
Taking a queue and building it as follows :
eg : if the tree is
1 / \ 2 3 / \ 4 5
Then we make the queue as following :
1-> NULL -> 2 -> 3 -> NULL -> 4 -> 5 -> NULL
Now all we have to do is just connect them, here is the code :
#define node TreeLinkNode
void Solution::connect(TreeLinkNode* root)
{
if(root==NULL) return ;
queue<node *> q;
q.push(root);
q.push(NULL);
while(!q.empty())
{
node *temp=q.front();
q.pop();
if(temp) temp->next=q.front();
else { if(!q.empty()) q.push(NULL); }
if(temp)
{
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
}
}