TreeNode *sortedArrayToBST(vector<int> &nums) {
int l = 0;
int r = nums.size()1;
if(r == 1)return NULL;// if there is no element
TreeNode *root = cr(nums,l,r);//create tree
return root;
}
TreeNode *cr(vector<int>nums,int l,int r){//function will return the root of tree
if(l > r)return NULL;
int mid = (l+r)/2; // take the mid element as root;
TreeNode *tmp = new TreeNode(nums[mid]);//create node with mid value
tmp>left = cr(nums,l,mid1); // recursively construct left subtree
tmp>right = cr(nums,mid+1,r);// and right sub tree
return tmp;
}
My code shows memory limit exceeded


I get it. Your problem is not relevant to the algorithm, but the implementation.
Pay attention to this statement
TreeNode *cr(vector<int>nums,int l,int r)
. You pass nums by value, not by reference, so every time you call the functioncr
, it will copy the big vector one more time. So in your recursion process, this behavior will cost large memory.