Can we optimize this solution further


  • 0
    R

    I tried the below simple recursive solution. Need help in optimizing this further. Please comment.

    TreeNode* sortedArrayToBSTHelper(vector<int>& nums, int st, int en) {
        
        int l = en - st + 1;
        
        if (l <= 0)
            return NULL;
        
        int mid = (st + en) / 2;
        TreeNode* result = new TreeNode(nums[mid]);
        result->left = sortedArrayToBSTHelper(nums, st, mid - 1);
        result->right = sortedArrayToBSTHelper(nums, mid + 1, en);
        return result;
    }
    
    TreeNode* sortedArrayToBST(vector<int>& nums) {           
        return sortedArrayToBSTHelper(nums, 0, nums.size() - 1);
    }

Log in to reply
 

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