My simple recursive C++ solution

  • 0

    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))
            root->left->next = root->right;
            if(root->next != NULL)
                root->right->next = root->next->left;

Log in to reply

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