-
Notifications
You must be signed in to change notification settings - Fork 0
/
avl.cpp
executable file
·136 lines (117 loc) · 3.11 KB
/
avl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "avl.h"
int Altura (pAVL *a)
{
int Alt_Esq, Alt_Dir;
if (a == NULL)
return 0;
else
{
Alt_Esq = Altura (a->esq);
Alt_Dir = Altura (a->dir);
if (Alt_Esq > Alt_Dir)
return (1 + Alt_Esq);
else
return (1 + Alt_Dir);
}
}
pAVL* RotacaoDireita(pAVL *pt){
pAVL* ptu;
ptu = pt->esq;
pt->esq = ptu->dir;
ptu->dir = pt;
pt->FB = 0;
pt = ptu;
return pt;
}
pAVL* RotacaoEsquerda(pAVL *pt){
pAVL* ptu;
ptu = pt->dir;
pt->dir = ptu->esq;
ptu->esq = pt;
pt->FB = 0;
pt = ptu;
return pt;
}
pAVL* RotacaoDuplaDireita (pAVL* pt){
pAVL* ptu, *ptv;
ptu = pt->esq;
ptv = ptu->dir;
ptu->dir = ptv->esq;
ptv->esq = ptu;
pt->esq = ptv->dir;
ptv->dir = pt;
if (ptv->FB == 1) pt->FB = -1;
else pt->FB = 0;
if (ptv->FB == -1) ptu->FB = 1;
else ptu->FB = 0;
pt = ptv;
return pt;
}
pAVL* RotacaoDuplaEsquerda (pAVL* pt){
pAVL *ptu, *ptv;
ptu = pt->dir;
ptv = ptu->esq;
ptu->esq = ptv->dir;
ptv->dir = ptu;
pt->dir = ptv->esq;
ptv->esq = pt;
if (ptv->FB == -1) pt->FB = 1;
else pt->FB = 0;
if (ptv->FB == 1) ptu->FB = -1;
else ptu->FB = 0;
pt = ptv;
return pt;
}
pAVL* InsereAVL(pAVL* a, int x) {
if (a == NULL) {
// A árvore está vazia, criamos um novo nodo com a informação x
pAVL* novo = (pAVL*) malloc(sizeof(pAVL));
novo->info = x;
novo->esq = NULL;
novo->dir = NULL;
novo->FB = 0;
return novo;
}
// A árvore não está vazia, devemos procurar o local correto para inserir o novo nodo
if (x < a->info) {
// O novo nodo deve ser inserido na subárvore esquerda
a->esq = InsereAVL(a->esq, x);
// Verifica se a inserção afetou o fator de balanceamento do nodo atual
if (Altura(a->esq) - Altura(a->dir) == 2) {
if (x < a->esq->info) {
a = RotacaoDireita(a);
} else {
a = RotacaoDuplaDireita(a);
}
}
} else {
// O novo nodo deve ser inserido na subárvore direita
a->dir = InsereAVL(a->dir, x);
// Verifica se a inserção afetou o fator de balanceamento do nodo atual
if (Altura(a->dir) - Altura(a->esq) == 2) {
if (x > a->dir->info) {
a = RotacaoEsquerda(a);
} else {
a = RotacaoDuplaEsquerda(a);
}
}
}
// Atualiza o fator de balanceamento do nodo atual
a->FB = Altura(a->esq) - Altura(a->dir);
return a;
}
pAVL* consultaAVL(pAVL *a, int chave) {
while (a!=NULL){
if (a->info == chave )
return a; //achou entao retorna o ponteiro para o nodo
else
if (a->info > chave)
a = a->esq;
else
a = a->dir;
}
return NULL; //se nao achou
}