C solution (6ms) - Iterative approach


  • 0
    void connect(struct TreeLinkNode *root) {
        if (!root) return;
        struct TreeLinkNode *parent = root, *child = root->left, *leftMostChild = root->left;
        while (parent && child) {
            child->next = parent->right;
            child = child->next;
            if (parent->next) {
                child->next = parent->next->left;
                child = child->next;
            }
            parent = parent->next;
            if (parent == NULL && leftMostChild) {
                parent = leftMostChild;
                child = leftMostChild = parent->left;
            }
        }
    }
    

Log in to reply
 

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