You are on page 1of 2

ARBORE AVL

# include <iostream.h>;
# include <conio.h>;
typedef struct nod{
int c,fe;
nod *st,*dr;
}NOD;
void rotatie_dreapta(NOD *&Rad,int &cr){
NOD *Fiu,*Nepot;
Fiu=Rad->st;
if(Fiu->fe==1){
Rad->st=Fiu->dr;
Fiu->dr=Rad;
Rad->fe=0;
Fiu->fe=0;
Rad=Fiu;
}
else{
Nepot=Fiu->dr;
Fiu->dr=Nepot->st;
Rad->st=Nepot->dr;
Nepot->st=Fiu;
Nepot->dr=Rad;
if(Nepot->fe==1){
Rad->fe=-1;
Fiu->fe=0;
}
else{
Rad->fe=0;
Fiu->fe=1;
}
Nepot->fe=0;
Rad=Nepot;
cr=0;
}}
void rotatie_stanga(NOD *&Rad,int &cr){
NOD *Fiu,*Nepot;
Fiu=Rad->dr;
if(Fiu->fe==-1){
Rad->dr=Fiu->st;
Fiu->st=Rad;
Rad->fe=0;
Fiu->fe=0;
Rad=Fiu;
}
else{
Nepot=Fiu->st;
Fiu->st=Nepot->dr;
Rad->dr=Nepot->st;
Nepot->st=Rad;
Nepot->dr=Fiu;
if(Nepot->fe==1){
Rad->fe=0;
Fiu->fe=-1;
}
else{
Rad->fe=1;
Fiu->fe=0;
}
Nepot->fe=0;
Rad=Nepot;
cr=0;

}}
void inserare_avl(NOD *&Rad,int x,int &cr){
if(Rad==NULL){
Rad=new NOD;
Rad->c=x;
Rad->fe=0;
Rad->st=NULL;
Rad->dr=NULL;
cr=1;
}
else
if(Rad->c==x){
cr=0;
}
else
if(x<Rad->c){
cr=0;
inserare_avl(Rad->st,x,cr);
if(cr==1)
switch(Rad->fe){
case -1: Rad->fe=0; cr=0; break;
case 0: Rad->fe=1; break;
case 1: rotatie_dreapta(Rad,cr); break;
}}
else{
cr=0;
inserare_avl(Rad->dr,x,cr);
if(cr==1)
switch(Rad->fe){
case 1: Rad->fe=0; cr=0; break;
case 0: Rad->fe=-1; break;
case -1: rotatie_stanga(Rad,cr);break;
}}}
void afisare(NOD *Rad,int nivel){
if(Rad!=NULL){
afisare(Rad->dr,nivel+1);
for(int i=0; i<=nivel; i++)cout<<" ";
cout<<Rad->c<<endl;
afisare(Rad->st,nivel+1);
}}
void main(){
clrscr();
NOD *Rad=NULL;
int n=0;
inserare_avl(Rad,0,n);
inserare_avl(Rad,17,n);
inserare_avl(Rad,18,n);
inserare_avl(Rad,15,n);
inserare_avl(Rad,25,n);
inserare_avl(Rad,10,n);
inserare_avl(Rad,6,n);
inserare_avl(Rad,60,n);
inserare_avl(Rad,13,n);
inserare_avl(Rad,34,n);
inserare_avl(Rad,23,n);
inserare_avl(Rad,26,n);
inserare_avl(Rad,3,n);
inserare_avl(Rad,15,n);
inserare_avl(Rad,19,n);
afisare(Rad,0);
getch();
}

You might also like