/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin)
{
int length_pre = pre.size();
int length_vin = vin.size();
if(length_pre <= 0 || length_vin <= 0 || length_pre != length_vin)
return NULL;
TreeNode * root = ConstructBinaryTree(pre, 0, length_pre -1, vin, 0, length_vin - 1);
return root;
}
TreeNode* ConstructBinaryTree(vector<int> pre,int prefirst, int preend, vector<int> vin, int vinfirst, int vinend)
{
if(prefirst > preend || vinfirst > vinend)
return NULL;
TreeNode * root = new TreeNode(pre[prefirst]);
//cout<<root->val<<" ";
//system("pause");
int p = -1;
for(int i = vinfirst; i <= vinend; i++)
{
if(vin[i] == pre[prefirst])
{
p = i;
break;
}
}
root->left = ConstructBinaryTree(pre, prefirst + 1, prefirst + p - vinfirst, vin, vinfirst, p - 1);
//root->right = ConstructBinaryTree(pre, prefirst + p + 1, preend, vin, vinfirst + p + 1, vinend);
root->right = ConstructBinaryTree(pre, prefirst + (p - vinfirst) + 1, preend, vin, p + 1, vinend);
return root;
}
};