剑指 Offer 07. 重建二叉树

/**
 * 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> mp;
    vector<int> pre, in;
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        pre = preorder, in = inorder;
        for(int i = 0; i < inorder.size(); i++)
            mp[inorder[i]] = i;
        TreeNode* root  = build(0, preorder.size() - 1, 0, inorder.size() - 1);
        return root;
    }

    TreeNode* build(int prel, int prer, int inl, int inr) {
        if(prel > prer) return NULL;
        int rootVal = pre[prel];
        int k = mp[rootVal], leftLen = k - inl;
        TreeNode* root = new TreeNode(rootVal);
        root->left = build(prel + 1, prel + leftLen, inl, k - 1);
        root->right = build(prel + 1 + leftLen, prer, k + 1, inr);
        return root;
    }
};
posted @ 2021-07-18 17:16  Dazzling!  阅读(19)  评论(0编辑  收藏  举报