/**
* 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* constructTree(vector<int>&preorder,vector<int>&inorder,int pre_start,int pre_end,int in_start,int in_end)
{
if(pre_start>pre_end)return NULL;
int cur_num=preorder[pre_start];
TreeNode* root=new TreeNode(cur_num);
int index;
for(int i=in_start;i<=in_end;i++)
{
if(inorder[i]==cur_num)
{
index=i;
break;
}
}
root->left=constructTree(preorder,inorder,pre_start+1,pre_start+index-in_start,in_start,index-1);
root->right=constructTree(preorder,inorder,pre_start+index-in_start+1,pre_end,index+1,in_end);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int len=preorder.size();
return constructTree(preorder,inorder,0,len-1,0,len-1);
}
};