My Iterative Solution in C++


  • -1
    J
    class Solution {
    

    public:

    void connect(TreeLinkNode *root) {
        if(!root)
            return;
        root->next = NULL;
        
        TreeLinkNode *first;
        TreeLinkNode *curr;
        TreeLinkNode *pre_curr;
        TreeLinkNode *pre_first = root;
    
        while(1)
        {
            while(pre_first && !pre_first->left && !pre_first->right)
                pre_first = pre_first->next;
            if(!pre_first)
                break;
            pre_curr = pre_first;
            first = pre_curr->left ? pre_curr->left : pre_curr->right;
            curr = first;
            while(pre_curr)
            {
                if(pre_curr->left)
                {
                    curr->next = pre_curr->left;
                    curr = curr->next;
                }
                if(pre_curr->right)
                {
                    curr->next = pre_curr->right;
                    curr = curr->next;
                }
                pre_curr = pre_curr->next;
            }
            curr->next = NULL;
            pre_first = first;
        }
    }
    

    };


Log in to reply
 

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