struct AVLNode;
typedef struct AVLNode *PAVLNode;
struct AVLNode {
KeyType key;
int bf;
PAVLNode llink,rlink;
};
typedef struct AVLNode *AVLTree;
typedef struct *PAVLTree;
int avlInsert(PAVLTree ptree, KeyType key)
{
PAVLNode node_a, node_b, parent_a,p,q, node;
int d;
if(*ptree == NULL) {
*ptree = createNode(key);
return 1;
}
node_a = p = *ptree;
parent_a = q =NULL;
while(p!=NULL) {
if(key == p->key) return 1;
if(p->bf != 0) {
parent_a = q;
node_a = p;
}
q = p;
if(key<p->key) p = p->llink;
else p=p->rlink;
}
node = createNode(key);
if(key<q->key) q->llink = node;
else q->rlink = node;
if(key<node_a->key) {
p=node_b=node_a->llink;
d = -1
}
else {
p = node_b = node_a->rlink;d = 1;
}
while(p!=node){
if(key<p->key){
p->bf = -1;
p=p->llink;
}
else {
p->bf =1;
p = p->rlink;
}
}
if(node_a->bf == 0){
node_a->bf = d;return 1;
}
if(node_a->bf == -d){
node_a->bf = 0;return 1;
}
if(d == -1)
if(node_b->bf == -1) node_b = lL(node_a, node_b);
else node_b = lR(node_a,node_b);
else
if(node_b->bf == 1) node_b = rR(node_a,node_b);
else node_b = rL(node_a,node_b);
if(parentp_a == NULL) *ptree = node_b;
else{
if(parent_a->llink == node_a) parent_a->llink = node_b;
else parent_a->rlink = node_b;
}
}
PAVLNode createNode (KeyType key){
PAVLNode node = (PAVLNode)malloc(sizeof(AVLNode));
if(node!=NULL) {
node->key = key;
node->bf = 0;
node->llink = node->rlink = NULL;
}
return node;
}
PVLNode lL(PAVLNode a,PAVLNode b){
a->bf = 0;
a->llink = b->rlink;
b->bf = 0;
b->rlink = a;
return b;
}
PAVLNode rR(PAVLNode a,PAVLNode b)
{
a->bf = 0;
a->rlink = b->llink;
b->bf = 0;
b->llink = a;
return b;
}
PAVLNode lR(PAVLNode a,PAVLNode b)
{
PAVLNode c = b->rlink;
a->llink = c->rlink;
b->rlink = c->llink;
c->llink = b;
c->rlink = a;
switch(c->bf){
case 0:a->bf = 0;b->bf = 0;break;
case -1:a->bf = 1;b->bf=0;break;
case 1:a->bf = 0;b->bf = -1;break;
}
c->bf = 0;return c;
}
PAVLNode rL(PAVLNode a,PAVLNode b)
{
PAVLNode c = b->llink;
a->rlink = c->llink;
b->llink = c->rlink;
c->llink = a;
c->rlink = b;
switch(c->bf){
case 0:a->bf = 0;b->bf=0;break;
case -1:a->bf=0;b->bf = -1;b->bf=1;break;
case 1:a->bf = -1;b->bf = 0;break;
}
c->bf = 0;
return c;
}