跳转至

从中序与后序遍历序列构造二叉树⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

/**
 * 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 {
private:
    unordered_map<int, int> pos;

    TreeNode* treeBuilder(vector<int>& inorder, vector<int>& postorder, int inL, int inR, int postL, int postR) {
        if (inL > inR) return nullptr;
        auto root = new TreeNode(postorder[postR]);
        int index = pos[root->val];

        root->left = treeBuilder(inorder, postorder, 
                        inL, index - 1,
                        postL, postL + index - 1 - inL);
        root->right = treeBuilder(inorder, postorder,
                        index + 1, inR,
                        postL + index - inL, postR - 1);
        return root;
    }

public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int treeSize = inorder.size();
        for (int i = 0; i < treeSize; i++) pos[inorder[i]] = i;
        return treeBuilder(inorder, postorder, 0, treeSize - 1, 0, treeSize - 1);
    }
};