AVL tree in C language
I am currently doing a project that requires using AVL trees, the insert function I wrote for avl doesn't seem to work, it works for 3 or 4 nodes maximum;
I am very grateful for your help Trying 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;
}
source to share
I don't know what kind of error you are getting, but there are a few things that need to be fixed.
You need to decide what you are going to do when it works malloc
. At the moment you are setting height
to a null pointer in this case.
If it height(NULL)
returns 0, you are setting the height at the new node to 0 and then to 1. If it returns -1, then one of those assignments is redundant.
And you call strcmp
twice for no good reason.
I suspect that the real problem is similar to s_rotate_left
, d_rotate_left
, s_rotate_right
or d_rotate_right
.
source to share