/**
* 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:
unordered_map<int,int> pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for(int i = 0;i < n;++i) pos[inorder[i]] = i; //pos中记录元素在中序中的位置
return dfs(preorder,inorder,0,n-1,0,n-1);
}
TreeNode* dfs(vector<int>& pre,vector<int>& in,int pl,int pr,int il,int ir){
if(pl > pr) return NULL;
//建树,找根节点,找左右子树,把左右树连接到根节点
TreeNode* root = new TreeNode(pre[pl]); //根节点是先序中的第一个点
int k = pos[pre[pl]] - il; //中序遍历中左子树的长度
root->left = dfs(pre,in,pl + 1,pl + k,il,il + k -1);
root->right = dfs(pre,in,pl + k + 1,pr,il + k + 1,ir);
return root;
}
};