编程语言
首页 > 编程语言> > 牛客网JZ7 重建二叉树C++(解题步骤图解)

牛客网JZ7 重建二叉树C++(解题步骤图解)

作者:互联网

题目描述

在这里插入图片描述

示例:

在这里插入图片描述

题目分析:

示例:
在这里插入图片描述
步骤分析:
在这里插入图片描述

代码:

class Solution {
public:
    TreeNode* reConstructBinaryTreeHelper(vector<int> &pre,int pre_start,int pre_end,vector<int> &vin ,int vin_start,int vin_end)
    {
        if(pre_start > pre_end || vin_start > vin_end) return nullptr;
        TreeNode *root = new TreeNode(pre[pre_start]);
        for(auto i = vin_start;i<=vin_end;i++)
        {
            if(pre[pre_start] == vin[i])//说明我们在中序中找到了根节点的位置[vin_start,i],i[i+1,vin_end]
            {
                root->left = reConstructBinaryTreeHelper(pre, pre_start+1, i-vin_start+pre_start,vin,vin_start,i-1);
                root->right = reConstructBinaryTreeHelper(pre, i-vin_start+pre_start+1,pre_end,vin, i+1,vin_end);
                break;
            }
        }
        return root;
    }
    
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.empty() || vin.empty() || pre.size() != vin.size()) 
            return nullptr;
        return reConstructBinaryTreeHelper(pre,0,pre.size()-1,vin,0,vin.size()-1);
    }
};

标签:pre,end,start,int,vin,C++,牛客,二叉树,return
来源: https://blog.csdn.net/sakeww/article/details/122769619