"root"未命名类型错误

'root' does not name a type error

本文关键字:错误 类型 未命名 root      更新时间:2023-10-16

编译以下C++代码时,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    TreeNode* construct(vector<int> nums,int start, int end)
    {
        if(start>end)
            return NULL;
        int i,index,v = INT_MIN;
        for(i=start;i<=end;i++)
            if(nums[i]>v)
            {
                v = nums[i];
                index = i;
            }
        }
        TreeNode* root = new TreeNode(v);
        root->left = construct(nums,start,index-1);
        root->right = construct(nums,index+1,end);
        return root;
    }
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return construct(nums,0,nums.size()-1);
    }
};

我收到以下错误:

Line 27: 'root' does not name a type

我收到了很多关于此错误的文章,但似乎都没有解决问题。使用 malloc(( 在这里也不起作用。

谢谢!!

编译器

不知道root变量的类型,因为它的定义被注释掉了。您还有一个支撑问题,因为for循环可能需要一个,因为您在if之后有一个闭合。

应该做一些事情,如下所示。

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
   };
class Solution {
    TreeNode* construct(vector<int> nums,int start, int end)
    {
        if(start>end)
            return NULL;
        int i,index,v = INT_MIN;
        for(i=start;i<=end;i++){ //here a missing brace
            if(nums[i]>v)
            {
                v = nums[i];
                index = i;
            }
        }
        TreeNode* root = new TreeNode(v);
        root->left = construct(nums,start,index-1);
        root->right = construct(nums,index+1,end);
        return root;
    }
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return construct(nums,0,nums.size()-1);
    }
};

因此,提供的示例非常不清楚,但这就是代码的格式

注意:我目前无法访问编译器来测试这一点。

在头文件中

解决方案.h

// Definition for a binary tree node.
struct TreeNode 
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution 
{
public:
   Solution();
   ~Solution();
   TreeNode* construct(vector<int> nums,int start, int end);
   TreeNode* constructMaximumBinaryTree(vector<int>& nums);
};

在 CPP 文件中

解决方案.cpp

Solution::Solution()
{
    // Init any members
}
Solution::~Solution()
{
    // Delete any members
}
TreeNode* Solution::construct(vector<int> nums,int start, int end)
{
    if(start>end)
        return NULL;
    int i,index,v = INT_MIN;
    for(i=start;i<=end;i++)
    {
        if(nums[i]>v)
        {
            v = nums[i];
            index = i;
        }
    }
    TreeNode* root = new TreeNode(v);
    root->left = construct(nums,start,index-1);
    root->right = construct(nums,index+1,end);
    return root;
}
TreeNode* Solution::constructMaximumBinaryTree(vector<int>& nums) 
{
    return construct(nums,0,nums.size()-1);
}