题解 | #重建二叉树#

重建二叉树

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);
    }
};

全部评论

相关推荐

不对是145个人…嗯…&nbsp;大家都没发现秋招提前批来了嘛..笑死我了
牛客39712426...:投了也是浪费时间,之前投米实习,除了浪费我时间写笔试题没有任何反馈,懒得投了
26届校招投递进展
点赞 评论 收藏
分享
06-25 09:33
厦门大学 Java
程序员饺子:现在日常估计没啥hc了,等到八月多估计就慢慢有了。双九✌🏻不用焦虑的
投递快手等公司7个岗位
点赞 评论 收藏
分享
代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
最近拿到了正浩的提前批offer感觉自己的实力得到了肯定,也给了我更多底气
搞机墨镜猫:正浩提前批官网好像就只有电力电子软硬件,哥们投的是这两个岗位吗
26届校招投递进展
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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