题解 | #重建二叉树#

重建二叉树

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

全部评论

相关推荐

27双非本,最近面试被挂麻了面试官说简历内容太简单了,技术栈要单独一行,各位佬有啥建议吗
LZStarV:项目太简单了,你像用什么开发的技术栈没必要写一句话,按点写就好了;有特色的比如说WebSocket、视频流这种狠狠吹,那就好看多了
点赞 评论 收藏
分享
10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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