后序中序倒推二叉树

传送门

class Solution {
public:
    unordered_map<int,int> pos;
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        for(int i=0;i<inorder.size();i++) pos[inorder[i]]=i;
        return build(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
        
    }
    
    TreeNode* build(vector<int>& inorder,vector<int>& postorder,int il,int ir,int pl,int pr){
        if(pr<pl) return NULL;
        auto root=new TreeNode(postorder[pr]);
        int k=pos[postorder[pr]];
        root->left=build(inorder,postorder,il,k-1,pl,pr-1-ir+k);
        root->right=build(inorder,postorder,k+1,ir,pr-1-ir+k+1,pr-1);
        return root;
    }
};

你可能感兴趣的:(C++数据结构,leetcode,算法,职场和发展)