[英]Inserting a node in a binary search tree
这是我声明的代码,似乎插入 function 有问题,我不明白。 对于初学者来说,这肯定会令人沮丧。 所以,这是我全局声明的结构节点指针,
struct node{
int data;
struct node *left;
struct node *right;
};
这是我全局声明的根节点,
struct node *root=NULL;
这是我声明的插入 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;
}
这就是我在 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;
}
}
在这里,我在我的代码中没有发现任何错误,但我在插入 function 中不断收到分段错误(代码转储)。 谁能告诉我这段代码有什么错误?
建议代码:
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.