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