我编写了以下代码来插入二叉搜索树,该搜索树可以有重复的条目,但对于较大的输入(例如大于 30),我会出现段错误......请帮助!重复的条目存储在节点的右分支中
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct vertex{
int num;
struct vertex* r;
struct vertex* l;
} node;
void insert(node* T,int x)
{
if(x < T->num)
{
if(T->l == NULL)
{
T->l = (node*)malloc(sizeof(node));
T->l->num = x;
printf("%4d ",x);
return;
}
else
{
insert(T->l,x);
}
}
else if(x >= T->num)
{
if(x == T -> num)
if(T->r == NULL)
{
T->r = (node*)malloc(sizeof(node));
T->r->num = x;
printf("%4d ",x);
return;
}
else
insert(T->r,x);
}
}
main()
{
srand((unsigned int)time(NULL));
int i,n,m,x;
node* T;
printf("n = ");
scanf("%d",&n);
printf("\nm = ",&m);
scanf("%d",&m);
printf("\n\n\n+++ Inserting %d random integers between 1 and %d\n",n,m);
x = 1 + rand() % m;
T = (node*)malloc(sizeof(node));
T->num = x;
printf("%4d (1)",x);
for(i=1;i<n;i++)
{
x = 1+rand() % m;
insert(T,x);
if(i%8 == 7)
printf("\n");
}
printf("\n\n");
}
最佳答案
malloc()
不会初始化内存,因此在分配后将其他成员设置为 NULL
或使用 calloc()
。如果没有这个,当您执行 T->l
或 T->r
时,您将访问随机内存。
T = malloc(sizeof(node));
T->num = x;
T->l = NULL;
T->r = NULL;
或
T = calloc(1, sizeof(node));
T->num = x;
在所有使用 malloc()
的地方执行此操作
关于c - 插入二叉搜索树时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18820765/