class Link
#ifndef _DFLIST_
#define _DFLIST_
template<typename E>class Link
{
private:
static Link<E>* freelist;
public:
E element;
E height;
Link<E>* lchild;
Link<E>* rchild;
Link(E elem)
{
element = elem; height = 1; lchild = rchild = NULL;
}
Link(const E& elemval, Link* preval , Link* nextval)
{
element = elemval; lchild = preval; rchild = nextval; height = 1;
}
Link(Link* preval = NULL , Link* nextval = NULL)
{
lchild = preval ; rchild = nextval; height = 1;
}
void* operator new (size_t)
{
if(freelist == NULL)return ::new Link;
Link<E>* tmp = freelist;
freelist = freelist -> rchild;
return tmp;
}
void operator delete (void* ptr)
{
((Link<E>*)ptr) -> rchild = freelist;
freelist = (Link<E>*)ptr;
}
};
template<typename E>
Link<E>* Link<E>::freelist = NULL;
#endif
AVLTREE
#ifndef _AVLTREE_
#define _AVLTREE_
#include "FLink.h"
template<typename E>class AVLTree : public Link
{
public:
void L(Link* &root)
{
Link* tmp = root -> rchild;
root -> rchild = tmp ->lchild;
tmp ->lchild = root ;
updateHeight(root);
updateHeight(tmp);
root = tmp;
}
void R(Link* &root)
{
Link* tmp = root ->lchild;
root ->lchild = tmp ->rchild;
tmp ->rchild = root ;
updateHeight(root);
updateHeight(tmp);
root = tmp;
}
void getHeight(Link* root)
{
if(root == NULL)return 0;
return root->height;
}
int getBalanceFactor(Link* root)
{
return getHeight(root->lchild) - getHeight(root->rchild);
}
void updateHeight(Link* root)
{
root->height = max (getHeight(root->lchild) - getHeight(root->rchild)) + 1;
}
void insert(Link* &root , int v)
{
if(root == NULL)
{
root = new Link<E>(v);
return;
}
if(v < root -> element)
{
insert(root -> lchild , v);
updateHeight(root);
if(getBalanceFactor(root) == 2)
{
if(getBalanceFactor(root -> lchild) == 1)
{
R(root);
}
else if(getBalanceFactor(root -> lchild) == -1)
{
L(root -> lchild);
R(root);
}
}
}
else{
insert(root -> rchild , v);
updateHeight(root);
if(getBalanceFactor(root) == -2)
{
if(getBalanceFactor(root -> rchild)== -1)
{
L(root);
}
else if(getBalanceFactor(root -> rchild) == 1)
{
R(root->rchild)
L(root);
}
}
}
}
Link* CreateTree(int data[] , int n)
{
Link<E>* root = NULL;
for(int i = 0 ; i < n ; i++)
{
insert(root , data[i]);
}
return root;
}
};
#endif