简体   繁体   中英

Inserting a node in a binary search tree

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM