/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型vector * @param vinOrder int整型vector * @return TreeNode类 */ unordered_map<int,int> hash; TreeNode*answer(int left1,int right1,int left2,int right2,vector <int> preOrder,vector <int> vinOrder) { if(left1<=right1 && left2<=right2) { int m=preOrder[left1]; int n=hash[m]; int len2=n-left2; TreeNode*root=new TreeNode(m); root->left=answer(left1+1,left1+len2,left2,n-1,preOrder,vinOrder); root->right=answer(left1+len2+1,right1,n+1,right2,preOrder,vinOrder); return root; } return NULL; } TreeNode* reConstructBinaryTree(vector<int>& preOrder, vector<int>& vinOrder) { int i=0; int len=preOrder.size(); for(i=0;i<len;i++) { hash[vinOrder[i]]=i; } i=0; return answer(i,len-1,i,len-1,preOrder,vinOrder); } };