6ms C solution use only an array


  • 0
    B
     struct TreeLinkNode * queue[99999];
     int pre;
     int p;
    void connect(struct TreeLinkNode *root) {
        if (root == NULL) return;
        pre = 0;
        p = 0;
        queue[p++] = root;
        while(pre != p){
            //printf("pre is %d , [pre] is %d , p is %d , [p-1] is %d\n" , pre , queue[pre]->val, p , queue[p-1]->val);
            int new_p = p;
            int new_pre = p;
            for (int tmp = pre;tmp < p;tmp++){
                if (queue[tmp]->left && queue[tmp]->right){
                    queue[new_p++] = queue[tmp]->left;
                    queue[new_p++] = queue[tmp]->right;
                }
                if (tmp + 1 < p){
                    queue[tmp]->next = queue[tmp+1];
                }else{
                    queue[tmp]->next = NULL;
                }
            }
            p = new_p;
            pre = new_pre;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.