剑指 Offer 07. 重建二叉树

2021年11月25日 阅读数:0
这篇文章主要向大家介绍剑指 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;
    }
};