嗨,大家好,我正在c中实现一个二叉搜索树。似乎插入树工作正常。但是当搜索时,它给出了分割失败。请查看我的代码,并说明出现此问题的原因以及解决方法。提前致谢。
以下是代码...
struct node{
int data;
struct node *leftChild;
struct node *rightChild;
};
struct node *root=NULL;
void insert(int data){
struct node *current=NULL;
if(root==NULL){
root=(struct node*)malloc(sizeof(struct node));
root->data=data;
printf("Root data:%d\n",root->data);
}else{
current=root;
//Searching the posistion
while(true){
if((current->data)<data){
current=current->rightChild;
}else{
current=current->leftChild;
}
if(current==NULL){
break;
}
}
struct node *tempData;
tempData=(struct node*)malloc(sizeof(struct node));
tempData->data=data;
tempData->leftChild=NULL;
tempData->rightChild=NULL;
current=tempData;
printf("Current data:%d\n",current->data);
}
}
struct node* search(int data){
sstruct node *current=root;
if(current==NULL){
return;
}else{
while(current->data!=data){
printf("%d",current->data);
if((current->data)<data){
current=current->rightChild;
}else{
current=current->leftChild;
}
//printf("Hello world!:%d\n",current->data);
if(current==NULL){
printf("%d",current->data);
return NULL;
}
}
return current;
}
}
我的main()方法是...
insert(10);
insert(20);
insert(4);
insert(16);
search(20);
最佳答案
在您的搜索功能中:
if (current==NULL){
printf("%d",current->data); //this is the place cause the seg fault.
return NULL;
}
当前指向NULL时,访问内存中一个NULL的地方将引起分段错误。