C solution: recursive 4 ms, iterative 4 ms


  • 0
    P

    recursive:

    void connect_helper(struct TreeLinkNode *left, struct TreeLinkNode *right) {
        if (!left)
            return;
    
        left->next = right;
        if (!left->right)
            return;
            
        left->right->next = right->left;
        right->right->next = right->next ? right->next->left : NULL;
            
        connect_helper(left->left, left->right);
        connect_helper(right->left, right->right);
    }
    
    void connect(struct TreeLinkNode *root) {
        if (!root)
            return;
        
        connect_helper(root->left, root->right);
    }
    

    iterative:

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

Log in to reply
 

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