二叉搜索树中增加结点的代码

来源:百度知道 编辑:UC知道 时间:2024/06/02 23:33:09
void Insert(struct Treenode *T,char *strg)
{
int flag;
if(T==NULL)
{
T=malloc(sizeof(struct Treenode));
if(T==NULL)
printf("Out of space");
else
T->string=strg;
}
else
{
flag=strcmp(strg,T->string);
if(flag <0)
Insert(T->left,strg);
else if(flag>0)
Insert(T->right,strg);
else
exit(0);
}
}

主要将字符串存到树的结点里面去,按照strcmp(),大的放右边,小的放左边(不考虑有一样的)
调用时就insert(Tree,&A[n]); Tree是一个组成树的结构体(结点)的指针,A[n]是某个存有字符串的字符数组

这样的函数哪里出错了?我用VC编译自动退出了……

你不能在判断到T==NULL时,才T=malloc...,这样数据结构并没有链接起来。应该是判断T->left==NULL,然后T->left=malloc...,这样才链接起来了。
void Insert(struct Treenode *T,char *strg)
{
int flag;
if(T==NULL)
{
T=malloc(sizeof(struct Treenode));
if(T==NULL)
printf("Out of space");
else
{
T->string=strg;
T->left=NULL;
T->right=NULL;
}
}
else
{
flag=strcmp(strg,T->string);
if(flag <0)
{
if(T->left==NULL)
{
T->left=malloc(sizeof(struct Treenode));
T->left->string=strg;
T->left->left=NULL;
T->left->right=NULL;
}
else Insert(T->left,strg);
}
else if(flag>0)
{
if(T->right==NULL)
{
T->right=malloc(sizeof(struct Treenode));
T->right->string=strg;
T->right->left=NULL;
T->right->right=NULL;
}
else Insert(T->right,strg);
}