以下代码在c ++中插入二进制搜索树有什么问题?

时间:2016-02-20 14:26:58

标签: c++ data-structures tree binary-tree binary-search-tree

以下代码在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)

另外,我需要帮助来理解错误。

2 个答案:

答案 0 :(得分:1)

在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和其他方法来提供适当的内存管理。

我错过了什么吗?

答案 1 :(得分:-1)

正如Slava所说,函数声明(和定义)缺少任何返回类型。在你的情况下,第9行应该成为:     void Insert(int value,node *root);

此外,node不是struct node类型。 您应该使用typedef struct foo{ ... } node;