Professional Documents
Culture Documents
de
Datos.
Grado
en
Ingeniera
Inform7ca,
Ingeniera
del
So;ware
e
Ingeniera
de
Computadores
ETSI
Inform7ca
Universidad
de
Mlaga
rboles
rboles AVL
rboles
binarios
Diccionarios
Signatura
y
axiomas
Implementacin
de
diccionarios
va
rboles
AVL.
:->
:/\
:\/
Var
No
Var
Var
Var
"p"
"q"
"q"
15
"p"
12
20
raz
2
es
padre
de
5
y
6
interno
2
5
es
un
hijo
de
2
hoja
6
es
un
hijo
de
2
9
4
Un camino
1
Un
arco
6 es hermano de 5
9
5
, Node 3 [ Node 7 [ ] ]
]
Una hoja
Suma
los
valores
de
los
nodos
4
sumT :: (Num a) => Tree a -> a
sumT Empty
= 0
sumT (Node x ts) = x + sum [sumT t | t <- ts]
Nivel 0
Nivel 1
etc.
4
Nivel 2
rbol
binario:
Cada
nodo
7ene
a
lo
sumo
dos
hijos
Los
hijos
se
denominan
hijo
izquierdo
e
hijo
derecho
n:
nmero
de
nodos
h:
altura
3
n
23
-1
h=
3
n= 7
1+log2(7) h 7
11
Right subtree
12
atLevelB _ EmptyB
= []
atLevelB 0 (NodeB x lt rt) = [x]
atLevelB n (NodeB x lt rt) = atLevelB (n-1) lt ++ atLevelB (n-1) rt
Nivel 0
Nivel 1
Nivel 2
13
16
17
18
elementos:
T(0)
=
1
T(n)
=
O(n)
+
2
T(n/2),
si
n
>
0
splitAt
es
O(n)
19
vip
22
isEmpty empty
-- q1
-- q2
-- q3
-- q4
en orden FIFO
Ejercicio:
probar
first $ enq 3 $ enq 1 $ enq 2 empty == 1
-- pq1
-- pq2
23
module DataStructures.PriorityQueue.LinearPriorityQueue
( PQueue
empty
-- :: PQueue a
isEmpty -- :: PQueue a -> Bool
enqueue -- :: (Ord a) => a -> PQueue a -> PQueue a
first
-- :: PQueue a -> a
dequeue -- :: PQueue a -> PQueue a
) where
data PQueue a = Empty | Node a (PQueue a)
empty :: PQueue a
empty = Empty
isEmpty :: PQueue a -> Bool
isEmpty Empty = True
isEmpty _
= False
enqueue :: (Ord a) => a -> PQueue a -> PQueue a
Los elementos son encolados
enqueue x Empty = Node x Empty
en orden ascendente
enqueue x (Node y q)
Recursivamente, encola
| y <= x
= Node y (enqueue x q)
x detrs de y
| otherwise
= Node x (Node y q)
24
first :: PQueue a -> a
first Empty
= error "first on empty queue"
first (Node x _) = x
El elemento mnimo
aparece al principio
dequeue :: PQueue a -> PQueue a
dequeue Empty
= error "dequeue on empty queue"
dequeue (Node _ q) = q
Ejercicio:
implementar
la
Cola
con
Prioridad
en
Java
usando
una
lista
enlazada
25
Operacin
Coste
empty
O(1)
isEmpty
O(1)
enqueue
O(n)
first
O(1)
dequeue
O(1)
su padre
Este no es
un heap L
Un heap J
0
Equivalentemente:
la
secuencia
de
nodos
de
cualquier
camino
desde
27
Un montculo
binario J
Este no es un
completo L
insert(0)
29
El resultado es un
rbol completo J
insert(0)
0
insert(0)
30
Para reestablecer la
propiedad HOP J
insert(0)
3
0
31
insert(0)
Swap 0 3
Para reestablecer la
propiedad HOP J
32
Para reestablecer la
propiedad HOP J
Un montculo
binario J
insert(0)
Swap 0 3
Swap 0 1
1
3
33
Nmero de pasos
300
250
Enorme
diferencia
entre
n
y
log
n
200
150
100
50
log n
N de nodos
34
7
Delete root
35
Intercambiar minChild(u) c on u
Reestablecer la
propiedad HOP J
7
Delete root
2
5
3
4
36
Reestablecer la
propiedad HOP J
Intercambiar minChild(u) c on u
7
Delete root
2
5
3
4
Swap 7 2
7
5
37
Reestablecer la
propiedad HOP J
Intercambiar minChild(u) c on u
Swap 7 2
Delete root
7
5
38
Reestablecer la
propiedad HOP J
Intercambiar minChild(u) c on u
El montculo
final J
Swap 7 2
Delete root
Swap 7 4
7
5
4
5
39
Nivel
0
Nivel
1
Nivel
2
b
d
0
a
Nivel l 0
1
b
2
c
3
d
4
e
Nivel 1
5
f
Nive l 2
f
hijos
0
a
1
b
2
c
3
d
4
e
5
f
padres
40
package dataStructures.heap;
public interface Heap<T extends Comparable<? super T>> {
boolean isEmpty();
El tipo T de los elementos del
montculo debe implementar
int
size();
el mtodo (relacin de orden)
compareTo
void
insert(T x);
T
minElem();
void
delMin();
}
41
package dataStructures.heap;
public class BinaryHeap<T extends Comparable<? super T>>
implements Heap<T> {
private T elems[];
private int size; // number of elements in heap
private static int INITIAL_CAPACITY = 128;
public BinaryHeap() {
elems = (T[]) new Comparable[INITIAL_CAPACITY];
size = 0;
}
private void ensureCapacity() {
if(size == elems.length)
elems = Arrays.copyOf(elems,2*elems.length);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
42
43
private int parent(int idx) { // index for parent of node with index idx
return (idx-1) / 2; // integer division
}
private int leftChild(int idx) { // index for left child of node with index idx
return 2*idx+1;
}
private int rightChild(int idx) { // index for right child of node with index idx
return 1+leftChild(idx);
}
private boolean isNode(int idx) { // true if idx corresponds to index of a node in tree
return idx<size;
}
private boolean hasLeftChild(int idx) { // true if node with index idx has a left child
return leftChild(idx)<size;
}
private boolean isLeaf(int idx) { //returns true if node with index idx is a leaf node
return !hasLeftChild(idx); // !hasLeftChild(idx) !hasRightChild(idx)
44
}
public T minElem() {
if(isEmpty())
throw new EmptyHeapException("minElem on empty heap");
else
return elems[ROOT_INDEX];
}
El mnimo siempre
se encuentra en la
raz J
46
Operacin
BinaryHeap
isEmpty
minElem
insert
delMin
Coste
O(1)
O(1)
O(1)
O(log
n)
O(log
n)
O(n) si redimensionamos
el array
48
h1 :: Heap Char
h1 = Node 'a' 6 (Node 'd' 3 (Node 'e' 1 Empty Empty)
(Node 'f' 1 Empty Empty))
(Node 'b' 2 (Node 'c' 1 Empty Empty)
Empty)
rbol con raz b'
con 2 elementos
49
Es un
WBLH J
Es un
WBLH J
50
module DataStructures.Heap.WeightBiasedLeftistHeap
( Heap
, empty
-- :: Heap a
, isEmpty -- :: Heap a -> Bool
, minElem -- :: Heap a -> a
, delMin
-- :: (Ord a) => Heap a -> Heap a
, insert
-- :: (Ord a) => a -> Heap a -> Heap a
) where
data Heap a = Empty | Node a Int (Heap a) (Heap a) deriving Show
empty :: Heap a
empty = Empty
isEmpty :: Heap a -> Bool
isEmpty Empty = True
isEmpty _
= False
minElem :: Heap a -> a
minElem Empty
= error "minElem on empty heap"
minElem (Node x _ _ _) = x
El mnimo del montculo
es la raz del arbol
51
lrs
t
log2(n+1)
Caso
base:
lh, q = weight rh
Caso base:
-}
55
Paso
induc7vo:
Sean
p
=
weight lh
y
q
=
weight rh
si
lrs lh
entonces
1 + lrs rh log2(p+q+2)
1 + log2(q+1) log2(p+q+2)
{- 1 = log2 2,
log x + log y = log (xy) -}
log2(2q+2) log2(p+q+2)
{- _ y log2 son montonas}
2q+2 p+q+2
{- p q
True
56
57
dos WBLHs
merge
=>
Queremos mezclar dos listas ordenadas para obtener una lista ordenada:
59
Necesitamos
una
funcin
auxiliar
para
construir
un
rbol
zurdo
a
par7r
de
otros
dos
y
de
un
valor:
node :: a -> Heap a -> Heap a -> Heap a
node x h h'
El de ms peso a la
| w >= w'
= Node x s h h'
izquierda
| otherwise = Node x s h' h
where
Manteniendo
el
w = weight h
invariante:
los
w' = weight h'
El resultado es zurdo,
pero no necesariamente
s = w + w' + 1
argumentos
son
zurdos
ordenado, salvo que 0
no supere a las raices
node 0
=>
60
Conservando
el
invariante:
los
argumentos
son
monYculos
zurdos
61
Conservando
el
invariante:
los
argumentos
son
monYculos
zurdos
x
merge
x'
=>
62
Conservando
el
invariante:
los
argumentos
son
monYculos
zurdos
x'
rh
h'
lh
merge
=>
63
x
merge
merge
=>
x'
Conservando
el
invariante:
los
argumentos
son
monYculos
zurdos
1
lh'
=>
rh'
merge
64
Conservando
el
invariante:
los
argumentos
son
monYculos
zurdos
1
merge
merge
=>
=>
x'
merge
65
module DataStructures.PriorityQueue.WBLeftistPriorityQueue
( PQueue
, empty
-- :: PQueue a
, isEmpty
-- :: PQueue a -> Bool
, first
-- :: PQueue a -> a
, dequeue
-- :: (Ord a) => PQueue a -> PQueue a
, enqueue
-- :: (Ord a) => a -> PQueue a -> PQueue a
) where
import qualified DataStructures.Heap.WeightBiasedLeftistHeap as H
data PQueue a = PQ (H.Heap a)
empty :: PQueue a
empty = PQ H.empty
isEmpty :: PQueue a -> Bool
isEmpty (PQ h) = H.isEmpty h
enqueue :: (Ord a) => a -> PQueue a -> PQueue a
enqueue x (PQ h) = PQ (H.insert x h)
first :: PQueue a -> a
first (PQ h) = H.minElem h
dequeue :: (Ord a) => PQueue a -> PQueue a
dequeue (PQ h) = PQ (H.delMin h)
66
Operacin
empty
isEmpty
minElem
merge
insert
delMin
Coste
O(1)
O(1)
O(1)
O(log
n)
O(log
n)
O(log
n)
El
resultado
es
similar
al
obtenido
con
monYculos
binarios
en
Java
va
arrays
67
n/4
mezclas de
montculos de 2
elementos
n/8
mezclas de
montculos de 4
elementos
1
mezcla de
montculos de
n/2 elementos
mergeLoop (mergePairs [
mergeLoop (mergePairs [
mergeLoop [
]) =>
]) =>
]) =>
] =>
69
[1,3,4,6,7,8,9]
heapToList
mkHeap
[6,3,8,1,4,7,9]
70
package dataStructures.heap;
public class WeigthBiasedLeftistHeap<T extends Comparable<? super T>>
implements Heap<T>{
root
protected static class Tree<E> {
E elem;
// elemento raz del MZ
int weight;
// peso o nmero de elementos
Tree<E> left; // hijo izdo
a 5
Tree<E> right; // hijo dcho
}
// referencia a la raz del montculo
d 3
b 1
protected Tree<T> root;
public WeigthBiasedLeftistHeap() {
root = null;
}
e 1
f 1
public boolean isEmpty() {
return root == null;
significa null
}
private static<T> int weight(Tree<T> t) {
return t==null ? 0 : t.weight;
}
public int size() {
return isEmpty() ? 0 : root.weight;
}
71
h, Tree<T> hp) {!
72
"T x = h.elem;!
"T xp = hp.elem;!
"if (x.compareTo(xp) <= 0) {
// x <= xp!
"
"return node(x, h.left, merge(h.right, hp));!
"} else {!
"
"return node(xp, hp.left, merge(h, hp.right));
"
"
"!
"}!
merge :: (Ord a) => Heap a -> Heap a -> Heap a
merge Empty h'
= h'
merge h
Empty = h
merge h@(Node x w lh rh) h'@(Node x' w' lh' rh')
| x <= x'
= node x lh (merge rh h')
| otherwise
= node x' lh' (merge h rh')
73
return h1;
}
74
public T minElem() {
if(isEmpty())
throw new EmptyHeapException("minElem on empty heap");
else
return root.elem;
El mnimo en la raz
}
public void delMin() {
if(isEmpty())
throw new EmptyHeapException("delMin on empty heap");
else
Mezclamos los hijos
sin la raz
root = merge(root.left,root.right);
}
public void insert(T x) {
Tree<T> tree = new Tree<T>();
tree.elem = x;
tree.weight = 1;
root = merge(root, tree);
}
Creamos un nuevo MZ
con un solo elemento
La insercin se produce
al mezclar la raz con el
nuevo MZ
75
Un
BST
(Binary
Search
Tree)
es
un
rbol
binario
tal
que
para
cada
nodo
v,
todos
los
elementos
del
subrbol
Invariante de un BST
data BST a = Empty | Node a (BST a) (BST a) deriving Show
isBST :: (Ord a) => BST a -> Bool
isBST Empty
= True
isBST (Node x lt rt) = forAll (<x) lt && forAll (>x) rt
&& isBST lt && isBST rt
where
forAll :: (a -> Bool) -> BST a -> Bool
forAll p Empty
= True
forAll p (Node x lt rt) = p x && forAll p lt && forAll p rt
76
insert 7
77
7 debe quedar a la
derecha de 4
78
79
7 a la derecha de 6
80
7 debe quedar
aqu
81
82
Si x'==x, entonces
x es sustituido por x'
Altura en O(log n) J
Altura en O(n) L
83
84
85
[1,3,4,6,7,8,9]
inOrderB
mkBST
[9,7,4,1,8,3,6]
86
Maybe
search 4
search 10
87
:: BST a -> a
Empty
(Node x Empty rt)
(Node x lt rt)
Mnimo
elemento
88
:: BST a -> a
Empty
(Node x lt Empty)
(Node x lt rt)
Mximo
elemento
89
=>
delete 'c'
hoja
90
Solo 1 hijo
delete b'
=>
91
=>
delete d'
Hijo derecho
Mnimo del
hijo derecho
92
=>
delete d'
Hijo izquierdo
Mximo del
hijo izquierdo
93
split
=>
94
Mnimo
elemento del
rbol derecho
el elemento
mnimo
95
Operacin
empty
isEmpty
insert
isElem
delete
minim
maxim
Coste
O(1)
O(1)
O(n)
O(n)
O(n)
O(n)
O(n)
Ser
interesante
disponer
de
una
interfaz
para
dis7ntas
versiones
de
los
BST
(los
puros
y
los
equilibrados
AVL)
package dataStructures.binarySearchTree;
import dataStructures.tuple.Tuple2;
public interface SearchTree<K extends Comparable<? super K>, V> {
public boolean isEmpty();
public int size();
Implementaremos
una
variante
en
la
public int height();
que
cada
nodo
del
rbol
guarda,
adems
public void insert(K k, V v);
de
las
referencias
a
los
hijos,
otros
dos
public V search(K k);
datos:
una
clave
y
un
valor.
public boolean isElem(K k);
public void delete(K k);
Los
nodos
en
el
rbol
estarn
ordenados
public Iterable<K> inOrder();
public Iterable<K> postOrder();
segn
sus
claves.
public Iterable<K> preOrder();
public Iterable<V> values();
public Iterable<Tuple2<K,V>> keysValues();
97
package dataStructures.binarySearchTree;
public class BST<K extends Comparable<? super K>, V> implements SearchTree<K,V> {
private static class Tree<K,V> {
private K key;
private D value;
private Tree<K,V> left, right;
public Tree(C k, V v) {
key = k;
value = v;
left = null;
right = null;
}
}
private Tree<K,V> root;
private int size;
public BST() {
root = null;
size = 0;
}
public boolean isEmpty() {
return root == null;
}
public int size () {
return size;
}
98
temp.key = node.key;
temp.value = node.value;
return node.right; // devuelve el hijo derecho
} else {
// elimina el mnimo de la subrama izquierda
101
102
Recordemos
las
interfaces:
interface Iterable<T> {
public
Iterator<T> iterator();
}
public interface Iterator<T> {
boolean hasNext();
T next();
void remove();
}
}
Consideraremos
cinco
mtodos
para
generar
un
objeto
del
7po
Iterable<*>
para
recorrer
(iterar)
un
BST,
manipulando
claves,
valores,
o
ambos,
u7lizando
los
recorridos
estndar:
-
Por
claves
Preorden:
PostOrden:
InOrden:
Iterable<K> preOrder();
Iterable<K> postOrder();
Iterable<K> inOrder();
-
Por
valores:
Iterable<V> values();
-
Por
pares
(clave,
valor):
Iterable<Tuple2<K,V>> keysValues();
103
System.out.println("InOrder traversal:");
Iterator<Integer> it = bst.inOrder().iterator();
Devuelve un iterador que
while(it.hasNext())
recorre las claves del rbol
System.out.printf("%d ",it.next());
en orden
System.out.println();
System.out.println(KeysValues inOrder traversal:");
for(Tuple<Integer.String> par : bst.keysValues()) {
1 one
System.out.printf("%d %s", par._1(), par._2() );
2 two
3 three
}
5 five
System.out.println();
7 seven
104
root
Visitaremos la subrama
izquierda en primer lugar
(red)
Visitaremos el nodo en
segundo lugar (blue)
stack
Visitaremos la subrama
derecha en tercer lugar
(red)
nextTree =>
}
stack
106
t
nextTree =>
}
stack
107
t
nextTree =>
}
stack
108
t
nextTree =>
}
stack
109
t
nextTree =>
}
stack
110
t
nextTree =>
}
stack
111
t
nextTree =>
}
stack
112
t
nextTree =>
}
stack
113
t
nextTree =>
}
stack
114
t
nextTree =>
}
stack
115
t
nextTree =>
}
stack
116
t
nextTree =>
}
stack
117
t
nextTree =>
}
stack
118
t
nextTree =>
}
stack
119
t
nextTree =>
}
stack
120
t
nextTree =>
}
stack
121
t
nextTree =>
}
stack
122
t
nextTree =>
}
stack
123
t
nextTree =>
}
stack
124
EJEMPLO
if(either.isLeft())
Integer n = either.left();
Devuelve el Integer de
either
true si either
guarda un String
if(either.isRight())
String s = either.right();
Devuelve el String de
either
125
package dataStructures.either;
public interface Either<A,B> {
boolean isLeft();
boolean isRight();
A left();
B right();
}
public class Left<A,B> implements Either<A,B> {
private A left;
public Left(A x) { left = x; }
public boolean isLeft() { return true; }
public boolean isRight() { return false; }
public A left() { return left; }
public B right() { throw new NoSuchElementException("right on Left object"); }
public String toString() { return "Left("+left+")"; }
}
public class Right<A,B> implements Either<A,B> {
private B right;
public Right(B x) { right = x; } ...
126
}
No hay ms
elementos ya que el
stack est vacio
Inicializa el stack
while (either.isRight()) {
Tree<K,V> node = either.right();
save(node);
either = stack.top();
stack.pop();
Es un rbol de la izquierda. Nos
}
interesa solo la clave y el valor
return either.left();
127
if (node.left != null)
stack.push(new Right<Tree<K,V>, Tree<K,V>>(node.left));
clave y valor en
segundo lugar (left)
Visitamos el subrbol
izquierdo en primer
lugar (right)
128
129
Visitamos el
subrbol derecho en
if (node.right != null)
stack.push(new Right<Tree<K,V>, Tree<K,V>>(node.right)); segundo lugar (right)
if (node.left != null)
stack.push(new Right<Tree<K,V>, Tree<K,V>>(node.left));
Visitamos el subrbol
izquierdo en primer
lugar (right)
130
131
132
h|p://en.wikipedia.org/wiki/
AVL_tree
134
136
N(1)
=
1
rboles
AVL
trees
con
alturas
1,2
y
3
N(2)
=
2
N(h)
=
1
+
N(h
-
1)
+
N(h
-
2)
,
h
>
2
Nodo de la raz
de un rbol de
atura h
La altura de un
hijo debe ser
h -1
El nmero de oro
ecuacin
es la raz posi7va de la
x2 = 1 + x, es decir
1+ 5
=
= 1.618033988749895 ...
2
n+2 = n + n+1
138
1
(n ()n )
5
= lim
f n +1
fn
n = f n + f n 1
140
142
node 4
=>
143
lk
llt
lk
lrt
rt
llt
lrt
rt
144
lk
lk
rt
mayores
que 7
llt
menores
que 3
lrt
mayores
que 3 y
menores que 7
llt
menores
que 3
lrt
mayores
que 3 y
menores que 7
rt
mayores
que 7
145
lt
rlt
rk
rrt
lt
rk
rrt
lrt
146
lt
rk
menores
que 3
rlt
mayores
que 3 y
menores que 7
rk
rrt
mayores
que 7
rrt
mayores
que 7
lt
menores
que 3
rlt
mayores
que 3 y
menores que 7
147
insert 0
No necesita
rebalanceo
148
insert 0
2
149
insert 0
Necesita rotacin
simple rotR ya que
la altura del hijo es
dos unidades mayor
que la del hijo
derecho
150
insert 0
rotR
151
insert 7
No necesita
rebalanceo
152
insert
7
No necesita
rebalanceo
153
Necesita doble
rotacin
Inclinado a la
derecha
insert 7
154
insert 7
rotL
hijo
izquierdo
155
rotL
hijo
izquierdo
insert 7
156
h+1
h+2
insert
h
h+1
Tras la insercin la
rama izquierda se
descompensa
Ahora no es
un rbol AVL
L
h+2
Puede
volver
a
balancearse
con
una
simple
rotacin
h
h+1
h+2
158
h+1
h+2
insert
h
h+1
Tras la insercin, la
rama izquierda se
descompensa
Ahora no es
un rbol AVL
L
h+2
Puede
rebalancearse
con
una
doble
rotacin
h
h+1
h+2
159
h+1
h+2
insert
h
h+1
Ahora no es
un rbol AVL
L
Tras la insercin, la
rama derecha se
descompensa
h+2
Puede
rebalancearse
con
una
simple
rotacin
h
h+1
h+2
160
h+1
h+2
insert
h
h+1
Ahora no es
un rbol AVL
L
Tras la insercin, la
rama derecha se
descompensa
h+2
Puede
rebalancearse
con
una
doble
rotacin
h
h+1
h+2
161
162
(node k
(node k
(node k
(node k
k lt rt
lt rt)
(rotL lt) rt)
lt rt)
lt (rotR rt))
k
lt
rt
h+1
h+1
h+2
h+2
163
(node k
(node k
(node k
(node k
k lt rt
lt rt)
(rotL lt) rt)
lt rt)
lt (rotR rt))
k
lt
rt
h+1
h+1
h+2
h+2
164
k
lt
(node k
(node k
(node k
(node k
k lt rt
lt rt)
(rotL lt) rt)
lt rt)
lt (rotR rt))
rt
rotR (node k (rotL lt) rt)
h
h
h+1
h+1
h+2
h+2
Rotacin a la izquierda en
el subrbol izquierdo (lt)
h
h+1
h+2
Rotacin a la
derecha en la raz
165
lt rt)
(rotL lt) rt)
lt rt)
lt (rotR rt))
rt
lt
(node k
(node k
(node k
(node k
k lt rt
h+1
h+1
h+2
h+2
h
Rotacin a la derecha en el
subrbol derecho (rt)
h+1
h+2
Rotacin a la
izquierda en la raz
166
search 4
search 10
Maybe
167
Operacin
empty
isEmpty
insert
isElem
delete
minim
maxim
Coste
O(1)
O(1)
O(log
n)
O(log
n)
O(log
n)
O(log
n)
O(log
n)
package dataStructures.SearchTree;
public class AVL<K extends Comparable<? super K>, V> implements SearchTree<K,V>{
public Tree(C k, D v) {
key = k;
value = v;
height = 1;
left = null;
right = null;
}
}
public AVL() {
root = null;
}
170
public static int height(Tree<?,?> tree) {
return tree == null ? 0 : tree.height;
}
public boolean rightLeaning() {
return height(left) < height(right);
}
public boolean leftLeaning() {
return height(left) > height(right);
}
void setHeight() {
height = 1 + Math.max(height(left), height(right));
}
171
lrt
lt
lrt
this
9
172
rlt
rt
this
lrt
173
Tree<K,V> balanced;
174
175
178
Clave
5 "five"
2 "two"
1 "one"
9 "nine"
3 "three"
179
module DataStructures.Dictionary.AVLDictionary
( Dict
, empty
, isEmpty
, insert
, get
) where
import qualified DataStructures.BinarySearchTree.AVL as T
data Rel a b = a :-> b
Dos asociaciones son iguales
instance (Eq a) => Eq (Rel a b) where
sii tienen la misma clave
(k :-> _) == (k' :-> _) = (k == k')
instance (Ord a) => Ord (Rel a b) where
(k :-> _) <= (k' :-> _) = (k <= k')
180
181
Coste
O(1)
O(1)
O(log
n)
O(log
n)
182