My simple recursive C++ solution


  • 0
    G

    This is a very intuitive solution. If root is NULL or is a leaf node, don't do anything and just return.

    Else, set the left child's next pointer to the right child. And if the root's next hasn't been set yet, set the right child's next pointer to the root's next pointer's left child. And then recurse, first down the left and then down the right.

    void connect(TreeLinkNode *root) {
            if(!root || (!root->left && !root->right))
                return;
                
            root->left->next = root->right;
            
            if(root->next != NULL)
                root->right->next = root->next->left;
            
            connect(root->left);
            connect(root->right);
    }

Log in to reply
 

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