【发布时间】:2019-10-09 02:59:58
【问题描述】:
这是一个二叉搜索树实现,我想知道它有什么问题?
#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;
}
也许我的实现访问了一些我没有声明的内存。我刚刚创建了一个函数来插入一个节点和一个搜索函数,如果树没有匹配则返回。纠正我做错了什么。输出在我的 g++ 编译器中是分段错误(核心转储)。
【问题讨论】:
-
你没有在
insert里面给root分配内存。 -
@0x499602D2 谢谢。但是为什么我做 node *root=new node; 时它不起作用在我宣布root的课堂上。还有为什么当我搜索它说树为空的任何元素时我的树是空的。
标签: c++ linked-list tree binary-tree binary-search-tree