My C++ solution using recursive,with 25ms and O(1)memory


  • 1
    W
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if(root==NULL)
            return;
            root->next=NULL;
            create(root);
        }
        void create(TreeLinkNode *root)
        {
            if(root->left==NULL||root->right==NULL)
            return;
            TreeLinkNode* left=root->left;
            TreeLinkNode* right=root->right;
            left->next=right;
            if(root->next)
            {
                right->next=root->next->left;
            }else {
                right->next=NULL;
            }
            create(left);
            create(right);
        }
    };

  • 0
    F

    Please explain, how it is working.


  • 0
    D

    This is not real O(1) space complexity. Recursive solution takes space in stack.


Log in to reply
 

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