# Memory limit exceeded

• ``````//
``````

//> I am getting memory limit exceeded why ?Please help

``````/*
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {

public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int i=-1;

return(maketree(preorder,inorder,&i,0,inorder.size()-1));
}
TreeNode * maketree(vector <int> preorder,vector<int> inorder,int *index,int l,int r)
{
if(l>r)
return NULL;
(*index)++;
TreeNode *temp=NULL;
temp=(TreeNode *)malloc(sizeof(TreeNode));
temp->val=preorder[*index];//insert as root the first elememt of preorder
int i;
for(i=0;i<inorder.size();i++){
if(inorder[i]==preorder[*index])
break;
}
int pos_in_inorder_array=i;//look for the element in inorder array
temp->left=maketree(preorder,inorder,index,l,pos_in_inorder_array-1);//recurse left for left subtree
temp->right=maketree(preorder,inorder,index,pos_in_inorder_array+1,r);//recurse right for right //subtree
return temp;
}
};``````

• Your code is correct just one small change. You are passing the vectors by value. Every time the recursion happens a copy of your vectors are created. Just add '&' in your maketree function before preorder and inorder and everything will work.

``TreeNode * maketree(vector <int> &preorder,vector<int> &inorder,int *index,int l,int r)``

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