C++ 代码
/**
* 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) {
//第一次没ac出来,难受
for(size_t i=0;i<inorder.size();i++){
//这个记录的是该值
pos[inorder[i]]=i;
}
return reBuildTree( preorder, inorder,0,preorder.size()-1,0,preorder.size()-1);
}
TreeNode* reBuildTree( vector<int>& preorder, vector<int>& inorder,int pb,int pe,int is,int ie){
if(pb>pe){
return NULL;
}
TreeNode* root=new TreeNode(preorder[pb]);
int len=pos[preorder[pb]]-is;
root->left=reBuildTree( preorder, inorder,pb+1,pb+len,is,pos[preorder[pb]]-1);
root->right=reBuildTree( preorder, inorder,pb+len+1,pe,pos[preorder[pb]]+1,ie);
return root;
}
};