C++ gcc编译器中这个程序的输出是分段错误(内核转储)。我做错了什么?
这是一个二进制搜索树实现,我想知道它有什么问题?C++ gcc编译器中这个程序的输出是分段错误(内核转储)。我做错了什么?,c++,linked-list,tree,binary-tree,binary-search-tree,C++,Linked List,Tree,Binary Tree,Binary Search Tree,这是一个二进制搜索树实现,我想知道它有什么问题? #include<iostream> using namespace std; struct node { int data; node *left; node *right; }; class tree { node *root; public: tree() { root=NULL; } void insert(node *root,int key) {
#include<iostream>
using namespace std;
struct node
{
int data;
node *left;
node *right;
};
class tree
{
node *root;
public:
tree()
{
root=NULL;
}
void insert(node *root,int key)
{
if(root==NULL)
{
root->data=key;
root->left=NULL;
root->right=NULL;
}
else if(key<root->data)
{
node *temp = new node;
if(root->left==NULL)
{
root->left=temp;
temp->left=NULL;
temp->right=NULL;
}
else
{
insert(root->left,key);
}
}
else
{
node *temp=new node;
if(root->right==NULL)
{
root->right=temp;
temp->left=NULL;
temp->right=NULL;
}
else
insert(root->right,key);
}
}
void search(node *root,int key)
{
if(root==NULL)
cout<<"Tree is Empty";
else if(root->data==key)
cout<<"Match Found";
else if(key<root->data)
search(root->left,key);
else
search(root->right,key);
}
node* getHead()
{
return root;
}
};
int main()
{
tree a;
a.insert(a.getHead(),5);
a.insert(a.getHead(),3);
a.insert(a.getHead(),9);
a.insert(a.getHead(),11);
a.insert(a.getHead(),7);
a.search(a.getHead(),11);
return 0;
}
#包括
使用名称空间std;
结构节点
{
int数据;
节点*左;
节点*右;
};
类树
{
节点*根;
公众:
树()
{
root=NULL;
}
无效插入(节点*根,int键)
{
if(root==NULL)
{
根->数据=键;
根->左=空;
root->right=NULL;
}
else if(keydata)
{
node*temp=新节点;
如果(根->左==NULL)
{
根->左=温度;
temp->left=NULL;
temp->right=NULL;
}
其他的
{
插入(根->左,键);
}
}
其他的
{
node*temp=新节点;
如果(根->右==NULL)
{
根->右=温度;
temp->left=NULL;
temp->right=NULL;
}
其他的
插入(根->右,键);
}
}
无效搜索(节点*根,int键)
{
if(root==NULL)
cout您的问题在这一部分:
if(root==NULL)
{
root->data=key;
root->left=NULL;
root->right=NULL;
}
您对root执行一个空测试,然后继续访问root的成员,这将导致分段错误。因此,本质上,代码是:
if(root==NULL)
{
NULL->data=key;
NULL->left=NULL;
NULL->right=NULL;
}
最后,最好不要将与成员变量同名的变量传递到函数中。这会使代码很难读取和调试。因此,将“插入”和“搜索”中的变量“根”更改为“检查节点”,或者类似的东西。调试代码会容易得多。您没有在insert
@0x499602D2中分配内存给root
,谢谢。但是为什么在我声明root的类中,当我执行node*root=new node时,它不起作用。还有为什么当我搜索任何元素时,我的树是空的,它说树是空的。如您所述,这样做会导致错误基操作数'->'不是指针。这意味着null不是指针。这就是点。如果'root==null'为true,则访问'root'的a成员相当于尝试访问null中的成员。这仅用于说明目的。您不需要更改代码。首先要修复代码,您应该将“插入”和“搜索”中的局部变量更改为不使用成员变量名“root”。之后,调试将变得更容易。