简体   繁体   English

在二叉搜索树中插入一个节点

[英]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.这是我声明的代码,似乎插入 function 有问题,我不明白。 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这是我声明的插入 function

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()这就是我在 main() 中调用插入 function 的方式

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.在这里,我在我的代码中没有发现任何错误,但我在插入 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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