zoukankan      html  css  js  c++  java
  • 剑指 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;
        }
    };
    
  • 相关阅读:
    linux 命令
    linux 后门防范
    linux date
    shell 常用参数
    linux rule策略
    vlan对服务器要注意的事情
    STL vector——c++
    蛇形矩阵
    简单a+b
    小 X 与数字(ten)
  • 原文地址:https://www.cnblogs.com/fxh0707/p/15027072.html
Copyright © 2011-2022 走看看