Any C++ solution better than 20ms? here are my recursive one


  • 0
    B
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            if (!nums.size()){
                return nullptr;
            }
            int size = nums.size();
            TreeNode* root = new TreeNode(0);
            if (size==1){
                root->val = nums[0];
                return root;
            }
            root->val = nums[size/2];
            if (size/2 > 0){
                vector<int> left(nums.begin(), nums.begin()+size/2);
                root->left = sortedArrayToBST(left);
            }
            if (size/2+1 < size){
                vector<int> right(nums.begin()+size/2+1, nums.end());
                root->right = sortedArrayToBST(right);
            }
            return root;
        }
    };

  • 1
    J

    my 16ms solution :

    class Solution {
        TreeNode * helper(vector<int>& nums, int s, int e) {
            if(s>e)
                return NULL;
            
            int mid = (s + e) / 2;
            TreeNode *node = new TreeNode(nums[mid]);
            node->left = helper(nums, s, mid - 1);
            node->right = helper(nums, mid + 1, e);
            
            return node;
        }
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return helper(nums, 0, nums.size() - 1);
        }
    };
    

    you needn't check the size of the array~


  • 0
    S

    Yes, 16ms. Your solution unnecessarily create copies for the subarrays. All the call frames in your recursive call stack can just refer to the same vector<int>& object, and keep track of start and end indices, instead. That way, you avoid the work (time and space) in creating copies for the subarrays.


Log in to reply
 

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