Cpp Simple (Move head to down gradually and cur towards right


#1
void Solution::connect(TreeLinkNode* root) {
    if(!root)return;
    // edge case
    if(!root->left && !root->right){
        root = NULL;
        return;
    }
    // head is the left most node in the lower level
    // prev is the cur previous int he lower level to which next is yet to be assigned 
   // cur is the current node in the upper level
    TreeLinkNode* head = root, *prev, *cur; 
    while(head){
        cur = head;
        prev = NULL;
        head = NULL; // very important otherwise outer loop will never finish
        while(cur){
            if(cur->left){
                if(!prev){
                    head = cur->left;
                }
                else{
                    prev->next = cur->left;
                }
                prev = cur->left;
            }
            if(cur->right){
                if(!prev){
                    head = cur->right;
                }
                else{
                    prev->next = cur->right;
                }
                prev = cur->right;
            }
            cur = cur->next;
        }
    }
}


#2

Very Nice and Simple Solution!!