O(N) giving TLE


#1
TreeNode* cal(int l,int r,vector<int> v)

{
if(l>r) return NULL;
if(l==r){
return new TreeNode(v[l]);
}
int mid=l+(r-l)/2;
TreeNode* root=new TreeNode(v[mid]);
root->left=cal(l,mid-1,v);
root->right=cal(mid+1,r,v);
return root;
}
TreeNode* Solution::sortedArrayToBST(const vector &A) {
if(A.size()==0) return NULL;
if(A.size()==1) return new TreeNode(A[0]);
//TreeNode* root=NULL;
return cal(0,A.size()-1,A);
}


#2

Pass vector V by reference instead of value…TreeNode*cal(int l, int r,const vector &V)


#3

Awesome bro, it worked. thanks alot!.


#4

Can you please explain, why const vector&V is needed. and if we are not passing by reference then why TLE is occuring.


#5

If not by reference, then all values will be copied which will take time.
If not modifying, always pass as const reference.