Bit lengthy...but a good CPP solution...have a look


#1

TreeNode* construct(vector &pre,vector &in,int ind,int start,int end)
{
if(start==end)
{
TreeNode* leaf=new TreeNode(pre[ind]);
return leaf;
}
TreeNode* root=new TreeNode(pre[ind]);
int mid;
for(int i=start; i<=end; i++)
{
if(in[i]==root->val)
{
mid=i;
break;
}
}
if(mid>start)
root->left=construct(pre,in,ind+1,start,mid-1); // left subtree
if(mid<end)
root->right=construct(pre,in,ind+mid-start+1,mid+1,end); // right subtree
return root;
}
TreeNode* Solution::buildTree(vector &A, vector &B) {
int n=B.size();
return construct(A,B,0,0,n-1);
}