Reputation: 25
This is the code I have declared, it seems there's a problem with the insert function and I dont get it. And it sure gets depressing for a beginner. So, this is the struct node pointer that I declared globally,
struct node{
int data;
struct node *left;
struct node *right;
};
This is the root node I declared globally,
struct node *root=NULL;
This is the insert function that I have declared
int insert(struct node* p, struct node *newnode){
if(p==NULL){
p=newnode;
p->left=NULL;
p->right=NULL;
}
else{
if(newnode->data<p->data){
insert(p->left, newnode);
}
else if(newnode->data>p->data){
insert(p->right, newnode);
}
}
return 0;
}
And this is how I called the insert function in the main()
struct node *newnode;
while(1){
switch(n){
case 1:
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the element: ");
scanf("%d", &newnode->data);
insert(root, newnode);
default:
return 0;
}
}
Here I dont find anything wrong in my code, but i keep getting the segmentation error (code dumped) in the insert function. Can anyone please tell me what is the error in this code?
Upvotes: 0
Views: 266
Reputation: 11209
Proposed code:
int insert(struct node* p, int value){
if (p==NULL) {
p = (struct node*)malloc(sizeof(struct node));
p->data = value;
p->left=NULL;
p->right=NULL;
}
else if(value < p->data)
p->left = insert(p->left, value); // p->left will only be modified if it is null, otherwise it will stay as is
else if(value >= p->data)
p->right = insert(p->right, value); // p->right will only be modified if it is null, otherwise it will stay as is
return p;
}
Upvotes: 1