Simple and Easy to understand (with comments)


#1
/**
 * 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 Solution::connect(TreeLinkNode* A) {
TreeLinkNode *curr=A;//curr level
TreeLinkNode *head=NULL;//Next level head
TreeLinkNode *pre=NULL;//Next level pre(Means by sitting on upper level we connect child)
while(curr!=NULL)
{
    while(curr!=NULL)//Join all nodes on current level.... 
    {
        if(curr->left!=NULL)
        {
            if(pre==NULL)
               head=curr->left;//head of next level(Means very first node of next level)....
            else
               pre->next=curr->left;
               pre=curr->left;
        }
        if(curr->right!=NULL)
        {
            if(pre==NULL)
            head=curr->right;//head of next level(Means very first node of next level)....
            else
            pre->next=curr->right;
            pre=curr->right;
        }
        curr=curr->next;//Go to the next node of same level....
    }
    // Congo we complete this level....
    // Now,Just do Same for all levels....  
    curr=head;
    head=NULL;
    pre=NULL;
}
}