class Solution {
public:
int search(vector<int> &inorder,int low,int high,int target)
{
int i=0;
for(i=low;i<=high;i++)
{
if(inorder[i]==target)
return i;
}
}
TreeNode* prein(vector<int> &preorder,vector<int> &inorder,int ilow,int ihigh)
{
static int preindex=0;
if(ilow>ihigh)
return NULL;
TreeNode *root=new TreeNode(preorder[preindex]);
preindex++;
if(ilow==ihigh)
return root;
int inindex=search(inorder,ilow,ihigh,root>val);
root>right=prein(preorder,inorder,inindex+1,ihigh);
root>left=prein(preorder,inorder,ilow,inindex1);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int p1=preorder.size();
int i1=inorder.size();
if(p1==0 && i1==0)
return NULL;
return prein(preorder,inorder,0,i11);
}
};
I am getting runtime error for [1,2,3,4],[1,2,3,4], although it's perfect in my compiler.


The problem comes from your
static int preindex = 0
.OJ will run all test case by running program only once, so your static variable will grow large during the entire process.
However, there is another bug in your code, would also bring to Runtime Error.
root>right=prein(preorder,inorder,inindex+1,ihigh); root>left=prein(preorder,inorder,ilow,inindex1);
You should swap their order, first left then right.