/**
* 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:
// vector<int> pos;之前这一步因为不能初始化导致segment
unordered_map<int,int> pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
//本来那种可以用pos.resize(n)来初始化
for(int i = 0;i<n;i++){
pos[inorder[i]] = i;//创建inorder相对位置的映射,再pos[preorder[i]]表示preorder中元素再inorder中元素的位置。
}
return dfs(preorder,inorder,0,n-1,0,n-1);
}
TreeNode* dfs(vector<int>& preorder, vector<int>& inorder,int pl,int pr,int il,int ir){
if(pl>pr) return NULL;
TreeNode* root = new TreeNode(preorder[pl]);
int k = pos[preorder[pl]] - il;
root->left = dfs(preorder,inorder,pl+1,pl+k,il,il+k-1);
root->right = dfs(preorder,inorder,pl+k+1,pr,il+k+1,ir);
return root;
}
};
每日一题day6