题解 | #重建二叉树#

重建二叉树

https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <cmath>
#include <vector>
class Solution {
public:
    TreeNode* reConstructBinaryTreeFunction(vector<int> pre,vector<int> vin, int pre_low,int pre_high, int vin_low, int vin_high){
        if(pre_high < pre_low || vin_low > vin_high) return nullptr;
        TreeNode* root = new TreeNode(pre[pre_low]);
        int mid = vin_low;
        for(int i = vin_low; i <= vin_high; i++){
            if(root->val == vin[i]) {
                mid = i;
                break;
            }
        }
        root->left = reConstructBinaryTreeFunction(pre, vin, pre_low + 1, pre_low + mid - vin_low, vin_low, mid - 1);
        root->right = reConstructBinaryTreeFunction(pre, vin, pre_low + mid - vin_low + 1, pre_high, mid + 1, vin_high);
        return root;
    }
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        return reConstructBinaryTreeFunction(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1);
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 11:15
点赞 评论 收藏
分享
05-29 20:34
门头沟学院 C++
KarlAllen:得做好直接春招的准备。学历差的话,一是面试要求会比学历好的严格不少,二是就算面试通过了也会被排序。总之暑期和秋招对于学历差的就是及其不友好
无实习如何秋招上岸
点赞 评论 收藏
分享
zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务