首页 > 其他 > 详细

剑指 Offer 07. 重建二叉树

时间:2021-02-09 22:19:11      阅读:27      评论:0      收藏:0      [点我收藏+]

技术分享图片

class Solution {

public:
    vector<int> pre;
    unordered_map<int,int> v;

    TreeNode* f(int root_pre_index,int l,int r){
        if(l>r) return nullptr;
        int i=v[pre[root_pre_index]];
        TreeNode* temp=new TreeNode(pre[root_pre_index]);

        int next_left_root=root_pre_index+1,
            next_right_root=root_pre_index+i-l+1;
            
        temp->left=f(next_left_root,l,i-1);
        temp->right=f(next_right_root,i+1,r);
        return temp;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        pre=preorder;
        int n=preorder.size();
        for(int i=0;i<n;++i){
            v[inorder[i]]=i;
        }
        return f(0,0,n-1);
    }
}

;

剑指 Offer 07. 重建二叉树

原文:https://www.cnblogs.com/Hunter01/p/14394256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!