class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
if(inorder.size()==0)
return NULL;
return traverse(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode *traverse(vector<int>&preorder,int pbegin,int pend,vector<int>&inorder,int ibegin,int iend)
{
if(pbegin>pend)
return NULL;
TreeNode *root=new TreeNode(preorder[pbegin]);
int index;
for(int i=ibegin;i<=iend;i++)
{
if(root->val==inorder[i])
{
index=i;
break;
}
}
TreeNode *left=traverse(preorder,pbegin+1,pbegin+index-ibegin,inorder,ibegin,index-1);
TreeNode *right=traverse(preorder,pbegin+index-ibegin+1,pend,inorder,index+1,iend);
root->left=left;
root->right=right;
return root;
}
};