问题
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;
}
回答1:
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
.
来源:https://stackoverflow.com/questions/2607456/avl-tree-in-c-language