/**
* 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* build(const vector<int>& inorder, int inStart, int inEnd, const vector<int>& preorder, int preStart, int preEnd, unordered_map<int,int>& inMap){
if(inStart > inEnd || preStart > preEnd){
return nullptr;
}
int rootVal = preorder[preStart];
TreeNode* root = new TreeNode(rootVal);
int inRoot = inMap[rootVal];
int numsLeft = inRoot - inStart;
root->left = build(inorder, inStart, inRoot - 1, preorder, preStart + 1, preStart + numsLeft, inMap);
root->right = build(inorder, inRoot + 1, inEnd, preorder, preStart + numsLeft + 1, preEnd, inMap);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int,int> inMap;
for(int i = 0; i < inorder.size(); ++i){
inMap[inorder[i]] = i;
}
TreeNode* root = build(inorder, 0, inorder.size() - 1, preorder, 0, preorder.size() - 1, inMap);
return root;
}
};