以下插入 c++ 二叉搜索树的代码有什么问题

What is wrong with the following code for insertion in a binary search tree in c++?

本文关键字:代码 什么 问题 搜索树 插入 c++      更新时间:2023-10-16

在 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;