leetcode:populating next right poniter in each node

key: two pointers,

one for the first node in each level

one for each node in one specific level   

                root

    p->  node1 node2

p->node3 node4 node5 node6

         |         |           |        | 

         q         q        q         q

 

 void connect(TreeLinkNode *root) {
        if(!root) return;
        root->next = NULL;
        TreeLinkNode* p = root;
        while(p->left){
            TreeLinkNode* q = p;
            while(q){
                q->left->next = q->right;
                if(q->next)
                    q->right->next = q->next->left;
                q = q->next;
            }
            p = p->left;
        }
    }

 

点赞