剑指 Offer 07. 重建二叉树
class Solution {
public:
vector<int> pre;
unordered_map<int,int> v;
TreeNode* f(int root_pre_index,int l,int r){
if(l>r) return nullptr;
int i=v[pre[root_pre_index]];
TreeNode* temp=new TreeNode(pre[root_pre_index]);
int next_left_root=root_pre_index+1,
next_right_root=root_pre_index+i-l+1;
temp->left=f(next_left_root,l,i-1);
temp->right=f(next_right_root,i+1,r);
return temp;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
pre=preorder;
int n=preorder.size();
for(int i=0;i<n;++i){
v[inorder[i]]=i;
}
return f(0,0,n-1);
}
}
;