segmentation fault while implementing the binary tree in C [closed]
I got a segmentation fault in the code when I am implementing the binary tree and couldn't figure out why.
#include <stdio.h>
#include <stdlib.h>
struct tree{
int info;
struct tree *lptr,*rptr;
};
typedef struct tree node;
node *create(int, node *);
node *insert(node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
int main(){
node *root=NULL;
int n,choice=0;
while(choice!=6){
printf("\n\n\t\tMENU");
printf("\n\t1:CREATE\n\t2:INSERTION\n\t3:POSTORDER");
printf("\n\t4:INORDER\n\t5:PREORDER\n\t6:EXIT");
printf("\n\n\tEnter your choice:\t");
scanf("%d",&choice);
switch(choice){
case 1:
printf("\n\tHow many elements to enter\t");
scanf("%d",&n);
root=NULL;
root=create(n,root);
return 0;
}
node *create(int n, node *root)开发者_开发百科{
int i;
for(i=0;i<n;i++)
insert(root);
return root;
}
node *insert(node *root){
int val;
node *temp, *p, *parent;
p=malloc(sizeof(node));
printf("\nEnter data for the node: ");
scanf("%d",&val);
p->info=val;
p->lptr=NULL;
p->rptr=NULL;
if(root=NULL)
root=p;
else{
temp=root;
while(temp){
parent=temp;
if(val<temp->info)
temp=temp->lptr;
if(val>temp->info)
temp=temp->rptr;
if(val==temp->info){
printf("Duplicate data!\n");
free(p);
break;
}
}
if(!temp&&p){
if(val<parent->info) //SEGMENTATION FAULT HERE!!!
parent->lptr=p;
if(val>parent->info)
parent->rptr=p;
}
}
return root;
}
void preorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
printf("%5d",root->info);
if(root->lptr)
preorder(root->lptr);
if(root->rptr)
preorder(root->rptr);
}
}
void inorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
if(root->lptr)
inorder(root->lptr);
printf("%5d",root->info);
if(root->rptr)
inorder(root->rptr);
}
}
void postorder(node *root){
if(root==NULL)
printf("\n\tEMPTY TREE!\n");
else{
if(root->lptr)
inorder(root->lptr);
if(root->rptr)
inorder(root->rptr);
printf("%5d",root->info);
}
}
Your problem is on these lines about 10 lines into your insert function:
if(root=NULL)
root=p;
You are assigning root to NULL instead of comparing it to NULL. Then, since NULL evaluates to false, root does not get assigned p. In fact those two lines guarantee that root is NULL after they execute. You just need to add an =
to make it a comparison like:
if(root == NULL)
root = p;
This is just an aside, but I recommend putting spaces around your comparison operators. It would make this error much more noticeable, and would make lines like: val>parent->info
much more readable, as that line could easily be mistaken for val->parent->info
Edit
As Mark pointed out in the comment below, since ==
is commutative, but =
isn't, you can also avoid this error by switching the order of the operands when you have a value on one side. If you put it on the left like (0 == root)
or (NULL == root)
. The compiler will catch the error for you if you leave an =
out since (0 = root)
is not syntactically correct.
精彩评论