/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
//遍历序列
int post_idx;
//哈希表
unordered_map<int, int>umap;
public:
TreeNode* helper(int in_left, int in_right, vector<int>& inorder, vector<int>& postorder){
//若空
if(in_left > in_right) return nullptr;
int root_val = postorder[post_idx];
//创建节点
TreeNode* root = new TreeNode(root_val);
int index = umap[root_val];
post_idx--;
//右子树
root->right = helper(index + 1, in_right, inorder, postorder);
//左子树
root->left = helper(in_left, index - 1, inorder, postorder);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
//开始序号
post_idx = postorder.size() - 1;
//
int idx = 0;
for(auto& innode : inorder){
umap[innode] = idx++;
}
//递归
return helper(0, postorder.size() - 1, inorder, postorder);
}
};