C++ iterative solution true o(1) memory 23ms


  • 3
    Y
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            TreeLinkNode* anchor = root;
            TreeLinkNode* curr = root;
            if (!root || !(root->left)) return;
            while(anchor){
                while(curr){
                    curr->left->next = curr->right;
                    if(!curr->next) break;
                    curr->right->next = curr->next->left;
                    curr = curr->next;
                }
                if(!anchor->left->left) break;
                curr = anchor = anchor->left;
            }
        }
    };

Log in to reply
 

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