劍指offer——重建二叉樹

baixiaofei567發表於2020-12-23

在這裡插入圖片描述
注意遞迴邊界即可,寫build函式記得把vector的引用傳進去更快
如果想看具體細節的可以看pat那裡的

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include<unordered_map>
class Solution {
public:
    unordered_map<int,int> ma;
    //前中構建二叉樹
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        for(int i = 0; i < vin.size(); i++){
            ma[vin[i]] = i;//第i位對應的值就是i,通過值找下標
        }
        TreeNode* node = build(0,pre.size()-1,0,vin.size()-1,pre,vin);
        return node;
    }
    TreeNode* build(int preL, int preR, int inL, int inR, const vector<int>& pre, const vector<int>& in){
        if(preL > preR) return nullptr;
        TreeNode* node = new TreeNode(pre[preL]);
        node->left = node->right = nullptr;
        int subLeftTree = ma[pre[preL]] - inL;
        node->left = build(preL+1, preL + subLeftTree, inL, inL+subLeftTree-1,pre,in);
        node->right = build(preL + subLeftTree +1, preR, inL+subLeftTree+1, inR,pre,in);
        return node;
    }
};

相關文章