You are on page 1of 3

#include "stdio.

h"
#include "conio.h"

struct Node {
int data;
int height;
Node *pLeft;
Node *pRight;
};

struct AVL {
Node *pRoot;
};

void KhoiTao(AVL &t)


{
t.pRoot = NULL;
}

int max(int a, int b)


{
return a > b ? a : b;
}

int chieuCao(Node *p)


{
return p == NULL ? 0 : p->height;
}

Node* XoayTrai(Node *p)


{
Node *temp = p->pRight;

p->pRight = temp->pLeft;
temp->pLeft = p;

p->height = 1 + max(chieuCao(p->pLeft), chieuCao(p->pRight));


temp->height = 1 + max(chieuCao(temp->pLeft), chieuCao(temp->pRight));

return temp;
}

Node* XoayPhai(Node *p)


{
Node *temp = p->pLeft;

p->pLeft = temp->pRight;
temp->pRight = p;

p->height = 1 + max(chieuCao(p->pLeft), chieuCao(p->pRight));


temp->height = 1 + max(chieuCao(temp->pLeft), chieuCao(temp->pRight));

return temp;

void Them(Node *&p, int x)


{
if (p == NULL)
{
Node *pNew = new Node;
pNew->data = x;
pNew->height = 1;
pNew->pLeft = pNew->pRight = NULL;

p = pNew;
return;
}

if (p->data == x) return;
else if (p->data > x) {
Them(p->pLeft, x);
} else Them(p->pRight, x);

int chieuCaoConTrai = chieuCao(p->pLeft);


int chieuCaoConPhai = chieuCao(p->pRight);
p->height = 1 + max(chieuCaoConTrai, chieuCaoConPhai);

int doLech = chieuCaoConTrai - chieuCaoConPhai;

if (doLech > 1) //mat can bang ben tay trai


{
int chieuCaoConTraiCuaConTrai = chieuCao(p->pLeft->pLeft);
int chieuCaoConPHaiCuaConTrai = chieuCao(p->pLeft->pRight);
if (chieuCaoConTraiCuaConTrai >= chieuCaoConPHaiCuaConTrai)
{ //lech trai
p = XoayPhai(p);
}
else { //lech phai
p->pLeft = XoayTrai(p->pLeft);
p = XoayPhai(p);
}
}

if (doLech < -1)


{ //mat can bang ben tay phai
int chieuCaoConTraiCuaConPhai = chieuCao(p->pRight->pLeft);
int chieuCaoConPhaiCuaConPhai = chieuCao(p->pRight->pRight);
if (chieuCaoConTraiCuaConPhai >= chieuCaoConPhaiCuaConPhai)
{ //lech trai
p->pRight = XoayPhai(p->pRight);
p = XoayTrai(p);

}
else { //lech phai
p = XoayTrai(p);
}
}

void NLR(Node *p)


{
if (p == NULL) return;

printf("%d ", p->data);


NLR(p->pLeft);
NLR(p->pRight);
}

void main()
{
AVL t;
KhoiTao(t);

Them(t.pRoot, 3);
Them(t.pRoot, 4);
Them(t.pRoot, 5);

NLR(t.pRoot);

_getch();
}

You might also like