1、题目
https://editor.csdn.net/md/?not_checkout=1
2、题意
题解1:哈希表记录中序值的索引
每次先序的第一个点为根 根据中序遍历找到跟节点的位置k
左子树在中序遍历中为il,k-1 在前序遍历中为pl+1,pl+1+k-1-il,il;
右子树在中序遍历中为k+1,ir 在前序遍历中为pl+1+k-1-il+1,pr;
/**
* 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) {
for (int i = 0; i < inorder.size(); i ++ ) pos[inorder[i]] = i;
return build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
}
TreeNode* build(vector<int>& pre,vector<int>& in,int pl,int pr,int il,int ir)
{
if(pl>pr) return NULL;
auto root = new TreeNode(pre[pl]);
int k = pos[pre[pl]];
root->left = build(pre,in,pl+1,pl+1+k-1-il,il,k-1);
root->right = build(pre,in,pl+1+k-1-il+1,pr,k+1,ir);
return root;
}
};