typedef struct avltreenode *avltree;
typedef struct avltreenode{
int data;
avltree left;
avltree right;
int height;
};
int getheight(avltree a)
{
if(a==NULL) return -1;
return a->height;
}
avltree singleleftrotation(avltree a)
{
avltree b=a->left;
a->left=b->right;
b->right=a;
a->height=max(getheight(a->left),getheight(a->right))+1;
b->height=max(getheight(b->left),a->height)+1;
return b;
}
avltree singlerightrotation(avltree a)
{
avltree b=a->right;
a->right=b->left;
b->left=a;
a->height=max(getheight(a->left),getheight(a->right))+1;
b->height=max(getheight(b->right),a->height)+1;
return b;
}
avltree doubleleftrightrotation(avltree a)
{
a->left=singlerightrotation(a->left);
return singleleftrotation(a);
}
avltree doublerightleftrotation(avltree a)
{
a->right=singleleftrotation(a->right);
return singlerightrotation(a);
}
avltree avl_insertion(int x,avltree t)
{
if(!t)
{
t=(avltree)malloc(sizeof(struct avltreenode));
t->data=x;
t->height=0;
t->left=t->right=NULL;
}
else if(x<t->data)
{
t->left=avl_insertion(x,t->left);
if(getheight(t->left)-getheight(t->right)==2)
{
if(x<t->left->data)
t=singleleftrotation(t);
else
t=doubleleftrightrotation(t);
}
}
else if(x>t->data)
{
t->right=avl_insertion(x,t->right);
if(getheight(t->left)-getheight(t->right)==-2)
{
if(x>t->right->data)
t=singlerightrotation(t);
else
t=doublerightleftrotation(t);
}
}
t->height=max(getheight(t->left),getheight(t->right))+1;
return t;
}