以下插入 c++ 二叉搜索树的代码有什么问题
What is wrong with the following code for insertion in a binary search tree in c++?
在 C++ 中插入二叉搜索树的以下代码有什么问题?
#include<iostream>
using namespace std;
struct node{
int value=0;
node *left=NULL,*right=NULL;
}*root=NULL;
Insert(int value,node *root);
InsertNode(int value,node *root);
int main()
{
Insert(5,root);
Insert(7,root);
Insert(3,root);
return 0;
}
Insert(int value,node *root)
{
if(root==NULL){
root=new node; root->value=value;cout<<endl<<value<<"inserted"<<endl;
}
else
{InsetNode(value,root);}
}
InsertNode(int value,node *root)
{
if(value<root->value){
root->left=new node;
Insert(value,root->left);
}
else{
root->right=new node;
Insert(value,root->right);
}
}
在 ubuntu 中使用 g++ 编译时会产生以下错误
9:29: error: expected constructor, destructor, or type conversion before ‘;’ token
Insert(int value,node *root);
^
10:33: error: expected constructor, destructor, or type conversion before ‘;’ token
InsertNode(int value,node *root);
^
In function ‘int main()’:
14:14: error: ‘Insert’ was not declared in this scope
Insert(5,root);
^
At global scope:
error: ISO C++ forbids declaration of ‘Insert’ with no type [-fpermissive]
Insert(int value,node *root)
^
In function ‘int Insert(int, node*)’:
error: ‘InsetNode’ was not declared in this scope
{InsetNode(value,root);}
^
At global scope:
29:32: error: ISO C++ forbids declaration of ‘InsertNode’ with no type [-fpermissive]
InsertNode(int value,node *root)
另外,我需要帮助来理解错误。
在C++函数的返回类型是必需的,不能省略:
void Insert(int value,node *root);
void InsertNode(int value,node *root);
函数定义也是如此。那是关于错误的。
现在对于程序样式:
- 使用同名的全局
- 变量和局部变量是自找麻烦的直接方法,你有同名的全局
root
和局部参数。 - 如果你仍然使用c ++ 11,你应该使用
nullptr
而不是NULL
-
using namespace std;
也不会使您的程序变得更好。 - 如果你用C++编写代码,你的类
node
应该有正确定义的ctor,dtor和其他方法来提供适当的内存管理。
我错过了什么吗?
正如 Slava 所说,函数声明(和定义)缺少任何返回类型。在您的情况下,第 9 行应变为: void Insert(int value,node *root);
此外node
不是struct node
的类型。您应该使用typedef struct foo{ ... } node;
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 需要以下代码的帮助,下面的代码有什么问题
- C++标准提案代码:什么是 N 和 P?
- C - 哈希算法代码什么都没有返回
- 将"12345678"转换为"1-234-5678",我的代码什么也没产生
- 在编译过程中,琐碎的(没有效果的)代码什么时候会被删除
- 有人能告诉我为什么这个代码什么都不打印吗