You are on page 1of 4

ARBORI AVL

//HEADER
#pragma once
typedef int Atom;
struct AVL {
Atom data;
int bf; //balance factor = h(stg)-h(drt)
AVL* stg, * drt;
};
void Echilibrare(AVL*& a, Atom x, bool stg);
AVL* MakeNodAVL(Atom x);
void InsertAVL(AVL*& rad, Atom x);
void AfisNod(AVL* r, int nivel);
void RSS(AVL*& a);
void RSD(AVL*& a);
void RDD(AVL*& a);
void RDS(AVL*& a);
void inordine(AVL* r);

//functii
#include <iostream>
#include"Header.h"
bool EqRequired;
using namespace std;
AVL* MakeNodAVL(Atom x)
{
AVL* p = new AVL;
p->data = x;
p->stg = 0;
p->drt = 0;
p->bf = 0;
return p;
}
void InsertAVL(AVL*& rad, Atom x)
{
if (rad == 0)
{
rad = MakeNodAVL(x);
EqRequired = true;
}

else
{
if (x < rad->data)
{
InsertAVL(rad->stg, x);
Echilibrare(rad, x, true);
}
else
{
if (x > rad->data)
{
InsertAVL(rad->drt, x);
Echilibrare(rad, x, false);
}
}
}

}
void Echilibrare(AVL*& a, Atom x, bool stg)
{
if (EqRequired)
{
if (stg == true)
{
switch (a->bf)
{

case 1:
EqRequired = false;
if (x < a->stg->data)
RSD(a);
else
RDD(a);
break;
case 0:
a->bf = 1;
break;
case -1:
a->bf = 0;
EqRequired = false;
break;
}

}
else
{
switch (a->bf)
{
case 1:
a->bf = 0;
EqRequired = false;
break;
case 0:
a->bf = -1;
break;
case -1:
EqRequired = false;
if (x > a->drt->data)
RSS(a);
else
RDS(a);
break;
}
}
}
else EqRequired = false;

}
void RSS(AVL*& a)
{
AVL* b;
b = a->drt;
a->drt = b->stg;
b->stg = a;
a->bf = b->bf = 0;
a = b; //b devine noua rad
}
void RSD(AVL*& a)
{
AVL* b = a->stg;
a->stg = b->drt;
b->drt = a;
b->bf = a->bf = 0;
a = b;
}
void RDD(AVL*& a)
{
AVL* b, * c;
b = a->stg;
c = b->drt;
switch (c->bf)
{
case 0:

a->bf = b->bf = 0;
break;
case -1:
a->bf = 0;
b->bf = 1;
break;
case 1:
a->bf = -1;
b->bf = 0;
}
a->stg = c->drt;
b->drt = c->stg;
c->bf = 0;
c->drt = a;
c->stg = b;
a = c;
}
void RDS(AVL*& a)
{
AVL* b, * c;
b = a->drt;
c = b->stg;
switch (c->bf)
{
case 0:
a->bf = b->bf = 0;
break;
case -1:
a->bf = 1;
b->bf = 0;
break;
case 1:
a->bf = 0;
b->bf = -1;
break;
}
a->drt = c->stg;
b->stg = c->drt;
c->bf = 0;
c->stg = a;
c->drt = b;
a = c;
}
void AfisNod(AVL* r, int nivel)
{
int i;
for (i = 0; i < nivel; i++)
cout << "\t";
if (r == 0)
cout << "-\n"; //pun "-" pentru nod vid
else
{
cout << r->data << endl;
AfisNod(r->stg, nivel + 1);
AfisNod(r->drt, nivel + 1);
}
}
void inordine(AVL* r)
{
if (r)
{
inordine(r->stg);
cout << r->data << " ";
inordine(r->drt);
}
}
//main

#include "Header.h"
#include <iostream>
using namespace std;

int main()
{
int x;
AVL* rad;
rad = 0;
cout << "Introduceti nodurile" << endl;
cin >> x;
while (x)
{
InsertAVL(rad, x);
cin >> x;
}
AfisNod(rad, 0);
inordine(rad);
return 0;

You might also like