根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
/**
* 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:
map<int, int> hash;
vector<int> preorder1;
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
preorder1 = preorder;
int n = inorder.size();
for (int i = 0; i < n; i++)
hash[inorder[i]] = i;
return dfs(0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode *dfs(int prel, int prer, int inol, int inor) {
if (prel > prer) return nullptr;
auto root = new TreeNode(preorder1[prel]);
int k = hash[root->val];
root->left = dfs(prel + 1, prel + k - inol, inol, k - 1);
root->right = dfs(prel + k - inol + 1, prer, k + 1, inor);
return root;
}
};