Share my O(n) space and O(nlgn) time cpp code with 26ms debated 97.6%


  • -1
    Y

    class Solution {
    TreeNode* sortedArrayToBST(vector<int>::iterator it_begin,vector<int>::iterator it_end){
    if(it_begin>it_end)
    return NULL;
    vector<int>::iterator mid=it_begin+(it_end-it_begin)/2;
    TreeNode* root=new TreeNode(mid);
    root->left=sortedArrayToBST(it_begin,mid-1);
    root->right=sortedArrayToBST(mid+1,it_end);
    return root;
    }
    public:
    TreeNode
    sortedArrayToBST(vector<int>& nums) {
    if(nums.size()==0)
    return NULL;
    TreeNode* root=sortedArrayToBST(nums.begin(),nums.end()-1);
    return root;
    }
    };


Log in to reply
 

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