Simple one loop 24ms solution


  • 0
    A
        void connect(TreeLinkNode *root) {
            TreeLinkNode *pred = NULL, *beg = root, *cur = root;
            while (beg) {
                if (pred) {
                    if (pred->left == cur) {
                        pred->left->next = pred->right;
                    } else if (pred->next) {
                        pred->right->next = pred->next->left;
                    }
                }
                
                if (pred) {
                    if (pred->next==NULL) { // next level
                        pred = beg;
                        beg = beg->left;
                        cur = beg; 
                    } else { // same level
                        if (pred->right == cur) 
                            pred = pred->next;
                        cur = cur->next;
                    }
                } else { // root
                    pred = beg;
                    beg = beg->left;
                    cur = beg;
                }
                
            }
        }
    

Log in to reply
 

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