Why it is showing Time Limit Exceeded


#1

TreeNode* bst(vector a,int s,int e)
{
if(s>e) return NULL;

int mid = (s+e) / 2;

TreeNode* r = new TreeNode(a[mid]);

r->left = bst(a,s,mid-1);
r->right = bst(a,mid+1,e);

return r;

}

TreeNode* Solution::sortedArrayToBST(const vector &a) {
return bst(a,0,a.size()-1);
}


#2

You are not passing the vector by reference in bst function. The way that you are passing vector each time a recursive function is called a new vector is formed and all values are copied which takes O(n) and whole process becomes O(nlog(n)) instead of O(n) . Pass vector by reference use const vector &a instead.