嘿所有; 我目前这样做需要使用AVL树的项目, 插入函数我写的AVL似乎并不奏效,它适用于3个或4个节点最大;
我真的AP preciate您的帮助 企图低于
树插入(树T,焦炭名[80],INT NUM)
{
如果(T == NULL)
{
T =(树)的malloc(的sizeof(结构节点));
如果(T!= NULL)
{
的strcpy(叔>的名称,姓名);
T-> NUM = NUM;
T->左= NULL;
T->右= NULL;
T->高度= 0;
}
}
否则如果(的strcmp(姓名,叔>名称)℃的)
{
T->左=插入(叔>左,姓名,NUM);
如果((高(叔>左)-height(叔>右))== 2)
如果(的strcmp(姓名,叔>左>名称)℃的)
T = s_rotate_left(T);
其他
T = d_rotate_left(T);
}
否则如果(的strcmp(姓名,叔>名称)大于0)
{
T->右=插入(叔>右,名,NUM);
如果((高(叔>右)-height(叔>左))== 2)
如果(的strcmp(姓名,叔>右>名称)大于0)
T = s_rotate_right(T);
其他
T = d_rotate_right(T);
}
叔>高度=最大值(高度(叔>左),高度(叔>右))+ 1;
返回吨;
}
解决方案
我不知道什么样的错误你得到,但也有几件事情需要加以固定。
您需要deside你打算怎么办时,的malloc
失败。现在你所设置高度
在这种情况下,一个空指针。
如果高度(NULL)
返回0,那么你一个新的节点上设置高度为0,然后到1。如果返回-1,然后是一个这些任务是多余的。
和你打电话 STRCMP
两次,没有充分的理由。
我怀疑真正的问题是埋在 s_rotate_left
, d_rotate_left
, s_rotate_right
或 d_rotate_right
。
Hey all; i am currently doing a project that requires the use of AVL trees , the insert function i wrote for the avl does not seem to be working , it works for 3 or 4 nodes at maximum ;
i would really appreciate your help The attempt is below
Tree insert(Tree t,char name[80],int num)
{
if(t==NULL)
{
t = (Tree)malloc(sizeof(struct node));
if(t! = NULL)
{
strcpy(t->name,name);
t->num = num;
t->left = NULL;
t->right = NULL;
t->height = 0;
}
}
else if(strcmp(name,t->name)<0)
{
t->left = insert(t->left,name,num);
if((height(t->left)-height(t->right))==2)
if(strcmp(name,t->left->name)<0)
t = s_rotate_left(t);
else
t = d_rotate_left(t);
}
else if(strcmp(name,t->name)>0)
{
t->right = insert(t->right,name,num);
if((height(t->right)-height(t->left))==2)
if(strcmp(name,t->right->name)>0)
t = s_rotate_right(t);
else
t = d_rotate_right(t);
}
t->height = max(height(t->left),height(t->right))+1;
return t;
}
解决方案
I don't know what sort of error you're getting, but there are a couple of things that need to be fixed.
You need to deside what you're going to do when the malloc
fails. Right now you are setting height
on a null pointer in that case.
If height(NULL)
returns 0, then you are setting the height on a new node to 0 and then to 1. If it returns -1, then one of those assignments is redundant.
And you're calling strcmp
twice for no good reason.
I suspect the real problem is buried in s_rotate_left
, d_rotate_left
, s_rotate_right
, or d_rotate_right
.