Memory limit exceeded. Please help

amazon
Tags: #<Tag:0x00007f1827b48e08>

#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    */

TreeNode* insert(TreeNode* A, int a)
{
TreeNode* temp = new TreeNode(a);
if(A == NULL) return temp;
else if(A->val > a)
{
A->left = insert(A->left,a);
}
else if(A->val < a)
{
A->right = insert(A->right,a);
}
return A;
}

TreeNode* Solution::sortedArrayToBST(const vector &A) {
int n = A.size();
TreeNode* root = NULL;
//int median = (n&1)?A[n/2]:((A[n/2]+A[n/2 - 1])/2);
if(n&1)
{
root = insert(root,A[n/2]);
for(int i=1;i<=n/2;i++)
{
root = insert(root,A[n/2+i]);
root = insert(root,A[n/2-i]);
}
}
else
{
for(int i=1;i<=n/2;i++)
{
root = insert(root, A[n/2+i-1]);
root = insert(root, A[n/2-i]);
}
}
return root;
}

Why is the memory limit exceeded for this code