编译C++最大二叉树代码遇‘root’ does not name a type错误求助
解决'root' does not name a type编译错误
你的问题出在多余的闭合大括号上,导致代码结构混乱,编译器无法正确识别变量的作用域。
错误原因分析
看你代码里的这段循环逻辑:
for(i=start;i<=end;i++) if(nums[i]>v) { v = nums[i]; index = i; } } // 这里多了一个额外的闭合大括号!
这个多余的}会提前结束construct函数,后面定义root、构建左右子树的代码就被误放到了类的成员声明区域。而在C++类中直接写执行语句(比如TreeNode* root = new TreeNode(v);)是不符合语法规则的,编译器自然会报错说root不是一个合法的类型。
修正后的完整代码
/** * 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); } };
小建议
写代码时可以借助IDE的括号匹配高亮功能(比如VS Code、CLion这类工具都会自动配对括号),写完循环、条件语句后检查一下括号是否成对,能有效避免这类低级语法错误。
内容的提问来源于stack exchange,提问作者Richa Tibrewal
相关产品推荐
相关产品推荐

