Professional Documents
Culture Documents
2013-1
rboles
Prof. Diego Arroyuelo
darroyue@inf.utfsm.cl diego.arroyuelo@usm.cl
rboles
Laslistasestudiadasenlaunidadanteriordelcursoson estructurasdedatoslineales:
Existeexactamenteunelementoprevioyotrosiguiente
Laslistastienenunalimitacinfundamental:
Olainsercin/borradooelaccesoaelementosarbitrarios sepuedehacerdeformaeficiente,peronoambos
Listasenlazadas:insercinyborradoentiempoO(1), accesoanodosarbitrariosentiempoO(n) Listassobrearreglos:insercinyborradoentiempoO(n), accesoanodosarbitrariosentiempoO(1)
rboles
rboles Listas
rboles
Lasestructurasderbolespermitentantoaccesoeficientealos elementosdelaestructuracomoactualizacindelamisma Enestetipodeestructurasnoexistesecuencialidadentrelos elementos,aunqueenlosarbolesexisteunaestructura jerarquica,demaneraqueunelementotieneunsolo predecesor,peropuedetenervariossucesores Dedicaremosestaunidadaestudiarestructurasdetiporbol
rboles
AlfinalizarlaUnidadelalumno: Conocerunafamiliacompletadeestructurasde tiporbol Sercapazdeimplementarestructurasdedatosde tiporbol Sercapazdereconoceraplicacionesquenecesiten elusoderbolesparasubuendesempeo
rboles
TemariodelaUnidad
Conceptoderbol,terminologabsica rbolesgenerales rbolesBinarios(AB) rbolesBinariosdeBsqueda(ABB) AVL rboles23 rbolesB,B+yB* Heapsycolasdeprioridad
Conceptos Principales
rboles
Losrbolessonunadelasestructurasmsusadasen informtica:
rbolessintcticosutilizadosporcompiladoresparainterpretar elementossintcticosdeunlenguaje,orepresentarexpresiones aritmticas(parachequeodetiposygeneracindecdigo) Representardatosparapermitirbsquedasyaccesoaellos relativamenterpido Sistemasdearchivos: Estructuradedirectoriosysubdirectoriosenformaderbolpara organizarlainformacin Diagramasdeclasesenprogramacinorientadaaobjetos Algoritmosdecompresindedatos Algoritmosdeordenamientodedatos
rboles: definicin
Unrbolestformadoporun conjuntofinitodeelementos, llamadosnodos Unodeesoselementoses identificadodemaneraespecial comolarazdelrbol Existeunarelacinpadrehijoque colocaalosnodosdelrbolenuna estructurajerrquica
Laestructuradedatosresultanteesnolineal: Cadanodopuedetenervariossucesoresenlaestructura Cadanodotieneunnicoantecesor
rboles: terminologa
Losnodossecalificandeacuerdoalaposicinqueocupen dentrodelrbol:
Siexisteuncaminodesdeelnodoualnodovenelrbol,entoncesvesun descendientedeu(yuesunancestrodev)
rboles: terminologa
rboles: terminologa
Gradodeunnodo:nmerodedescendientesdirectosdelnodo (nmerodesubrbolesonmerodehijosdelnodo) Conestadefinicin,elgradodeunahojaes0 Gradodelrbol:nmeromximodehijosquetienenlosnodos delrbol Unalistaesunrboldegrado1 rbolbinario:rboldegrado2(cadanodotienealoms2 descendientesdirectos) rbolmultiario:rboldegradomayora2(cadanodo puedetenermsde2hijos)
rboles: terminologa
rboles: terminologa
rboles: terminologa
rboles: terminologa
rboles: terminologa
rboles: terminologa
Recorridos en rboles
Recorridos en rboles
Muchasaplicacionesnecesitanprocesarunrbolvisitandosus nodos,yrealizandoaccionessobreellos
Porejemplo,mostrarsucontenido,osumarsuvalor,etc.
Haydosmanerastpicasderecorrerunrbol
Recorridoenprofundidad Recorridoenanchura
Enelcursoestudiaremoslasmanerasderecorrerrboles,as comosusprincipalesaplicaciones
Recorridos en rboles
Recorridoenanchura
Nivel0 Nivel1 Nivel2 Nivel3 4 9 2 5 6 10 11 7 1 3 8
Elrbolsevisitaporniveles:
Primerosevisitalaraz,ysecolocantodossushijosenunaestructuratipoCola Seprocededelamismamanera,tomandosiempreelprimernododelacola
Recorridos en rboles
Recorridoenprofundidad
Consisteenmoverseencadapasodelrecorridohacianodosde mayorprofundidadenelrbol,hastaquenosepuedaavanzaren esesentido(porquesealcanzunahoja) Sepuedenllevaracabodetresmanerasdiferentes: RecorridoPreorden RecorridoInorden RecorridoPosorden
Recorridos en rboles
RecorridoenPreorden
1. Visitarnodoactual 2. VisitarhijoizquierdoenPreorden 3. VisitarhijoderechoenPreorden
1 2 3 5 4 6 8 7 9
Recorridos en rboles
RecorridoenInorden
1. VisitarhijoizquierdoenInorden 2. Visitarnodoactual 3. VisitarhijoderechoenInorden
6 2 1 3 4 5 7 8 9
Recorridos en rboles
RecorridoenPostorden
1. VisitarhijoizquierdoenPostorden 2. VisitarhijoderechoenPostorden 3. Visitarnodoactual
9 5 1 2 4 3 6 8 7
Recorridos en rboles
Recorridosenprofundidad
Suelenimplementarsedemanerarecursiva Sinembargo,tambinpuedenimplementarsedemaneraiterativa usandopilascomoestructurasauxiliares Estudiaremosesasimplementacionesenelcurso
Posiblessoluciones:
Porcadanodo,almacenarunarregloconpunterosalosnodoshijo
Requieresaberdeantemanocuntoshijostendrcomomximounnodo. Sedesperdiciaespacioenlosnodosquetienenmenoshijosqueelmximo Accesoahijosarbitrariossepuedehacermuyeficientemente(O(1))
Porcadanodoalmacenarslodospunteros
PunteroalprimerhijoyPunteroalsiguientehermano Nodesperdiciaespacioparahijosquenoexisten,peroaccesoahijos arbitrariosnoeseficiente
hermano
hij
B E J F K
C G L P M Q
D H N I O
tipoElemgetValue(treeNode*N);
//almacenaunvalordentrodeunnodoN
voidsetValue(treeNode*N,tipoElemitem);
//obtieneelprimerhijodeunnodoN
treeNode*firstChild(treeNode*N);
//obtieneelsiguientehermanodeunnodo
treeNode*nextSibling(treeNode*N);
ApartirdeesteTDAunopuededefinirunrbolgeneral (Ejercicio!)
rboles Binarios
rboles Binarios
rboles Binarios
Laimplementacindeunrbolbinarioesmssimplequelade losrbolesgenerales
Cadanodoslodebemantener2punteros:
Punteroalhijoizquierdo Punteroalhijoderecho
PodemosimplementareltipoenC:
typedefstructnodoArbolBin{ tipoEleminfo; structnodoArbolBin*izq; structnodoArbolBin*der; }tNodoArbolBin;
rboles Binarios
ImplementacindeunrbolbinarioenC
Unrbolbinarioseidentificaconunpunteroasunodoraz,el cualdaaccesoatodalaestructura
typedefstruct{ tNodoArbolBin*raiz; intnElems; }arbolBin;
Distintos recorridos sobre el rbol permiten obtener la expresin aritmtica en diferentes notaciones
y
Elementos x < y
Elementos x > y
Al buscar por un elemento x': Si x' < y Buscarlo en el subrbol izquierdo Si x' > y Buscarlo en el subrbol derecho
16
30
19
29
32
12
17
21
Elementos entre 16 y 28
Implementacin de ABB
LassiguientessernlasoperacionessoportadasporelTDA tABB
//inicializaunABBcomovaco
voidinitTree(tABB*T)
//eliminatodosloselementosdeunABBT,dejndolovaco
voidclear(tABB*T);
//insertaunelementoitemenelABB
voidinsert(tABB*T,tipoElemitem);
//eliminaunelementoitemdeunABB
voidremove(tABB*T,tipoElemitem);
Implementacin de ABB
LassiguientessernlasoperacionessoportadasporelTDA tABB
//buscaunitemenunABBT,retorna0encasodenoencontrarlo
intfind(tABB*T,tipoElemitem);
//cantidaddeelementosenelrbol
intsize(tABB*T)
//recorridoinordendeunABBT
voidinOrden(tABB*T);
//recorridopreordendeunABBT
voidpreOrden(tABB*T);
//recorridopostordendeunABBT
voidpostOrden(tABB*T);
Implementacin de ABB
ImplementacindeltipotABBenC
typedefstruct{ tNodoArbolBin*raiz; //punteroalnodoraizdelABB intnElems; }tABB;
//cantidaddeelementosenelABB
ImplementacindelasoperacionesdelTDAtABB
//inicializaunABBcomovaco
Implementacin de ABB
ImplementacindelasoperacionesdelTDAtABB
//eliminatodosloselementosdeunABBT,dejndolovaco
clearHelp(nodo>izq); //visitasubrbolizquierdorecursivamente
//visitasubrbolderechorecursivamente
free((void*)nodo);//despusdeborrarsubrboles,seborraasmismo
Implementacin de ABB
ImplementacindelasoperacionesdelTDAtABB
//recorridoinordendeunABBT
Implementacin de ABB
ImplementacindelalgoritmodebsquedasobreunABB
Laideaesusarelordendeloselementosenelrbolparaguiarla bsquedaenelABB Seaxelelementobuscado Comenzandodesdeelnodorazdelrbol,serepitenlossig.pasos:
1. Sielnodoactualesrbolvaco(NULL)elementonoestenABB 2. Sixesigualalvaloralmacenadoenelnodoactualelemento encontrado,sedetienelabsqueda 3. Sixesmenoralvaloralmacenadoenelnodoactualcontinuarla bsquedaenelhijoizquierdodelnodoactual 4. Sixesmayoralvaloralmacenadoenelnodoactualcontinuarla bsquedaenelhijoderechodelnodoactual
Implementacin de ABB
ImplementacindelalgoritmodebsquedasobreunABB
//buscaunitemenunABBT,retorna0encasodenoencontrarlo
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Antesdeinsertarunnuevoelementox,debemosbuscarporlenelrbol Estotienedospropsitos
AsegurarsequexyanoseaunelementodelABB(asumimosquelos elementosnopuedenrepetirse) Encontrarelpuntodeinsercindex:elnuevoelementodeberaser insertadoenellugarendondelabsquedafall,porquedeesamanera podrserencontradocuandosebusqueporl.
Importante
LainsercindeunnuevoelementoenunABBdebepreservarlacondicin deordendelABB Lainsercindenuevoselementossiempreocurreaniveldelashojasdel rbol(nuncaentredosnodosyaexistentes,comoenlaslistas)
Implementacin de ABB
Ejemplo:supongamosquevamosainsertarelvalor20enesterbol
28
16 5 12 17 19 21
30 29 32
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Ejemplo:Paracadaunadelassiguientessecuencias,construirelABB correspondiente
10 5 7 14 12 18 15 15 18 14 5 10 12 7
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 10: 10
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 10 10
Insertar 5: 10 5
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 10 10
Insertar 5: 10 5
Insertar 7: 10 5 7
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 14: 10 5 7 14
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 14:| 10 5 7 14 5
Insertar 12: 10 14 7 12
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 14:| 10 5 7 14 5
Insertar 12: 10 14 7 12
Insertar 18: 10 5 7 12 14 18
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Para : 10 5 7 14 12 18 15
Insertar 15: 10 5 7
Ejercicio: Mostrar los valores almacenados en los nodos del ABB haciendo un recorrido in-orden del rbol
14 12 18
15
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Ejercicio:implementarlaoperacin
//insertaunelementoitemenelABB
voidinsert(tABB*T,tipoElemitem);
siguiendolaideaantesexplicada Ejercicio:Repetirelprocesodeinsercinparalasecuencia
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
AntesdeborrarunelementoxdeunABB,debemosbuscarporlenel rbol Estotienedospropsitos
AsegurarsequexseaunelementodelABB Encontrarelpuntodeborrado
Importante
ElborradodeelementoenunABBdebepreservarlacondicinde ordendelABB Adiferenciadelasinserciones,losborradospuedenocurriren cualquierpartedelrbol,nonecesariamenteenlashojas
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
Dependiendodelnodoaborrar,tenemostrescasos: 1. Borrarunnodohoja 2. Borrarunnodoquetieneunnicohijo 3. Borrarunnodoquetienedoshijos
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
Caso1:borrarunahojaseresuelveeleminandoelnododelrbol
28 28
16 5 12 17 borrar 29 21
30 32 5 12
16
30 29 21 32
19
19
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
Caso2:borrarunnodoquetieneunnicohijoseresuelve reemplazandoelnodoporsuhijo
28 28
16 borrar 19 17 21 29
30 32 17
19
30 29 32
21
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
Caso3:borrarunnodocondoshijosseresuelvereemplazandoel elementodelnodoporsusucesor/predecesor,yluegorecursivamente borrarelsucesor/predecesor(Caso1o2)
28 borrar 16 5 12 18 20 29
Sucesor de 28
25
30 32 5 12
16 29
30 32
25
Predecesor de 28
25 20 18
23
23
Implementacin de ABB
ImplementacindelalgoritmodeborradoenunABB
Caso3:borrarunnodocondoshijosseresuelvereemplazandoel elementodelnodoporsusucesor/predecesor,yluegorecursivamente borrarelsucesor/predecesor(Caso1o2)
25 25
16 5 12 18 20 29
30 32 5 12
16 20 18 23 29
30 32
25
23
Implementacin de ABB
ImplementacindelalgoritmodeinsercinenunABB
Ejercicio:implementarlaoperacin
//insertaunelementoitemenelABB
voidremove(tABB*T,tipoElemitem);
siguiendolaideaantesexplicada
rboles AVL
rboles AVL
LosABBbuscantenerbuentiempodebsqueda,yalavezbuen tiempodemodificacindelaestructuradedatos(insercin/borrado) Sinembargo,lacomplejidaddepeorcasodelasoperacionesno esmuybuena:
O(n)parabsquedaeinsercin/borrado
rboles AVL
Definicin
UnrbolbinariodebsquedaesAVLsi,paratodonododelrbol,la alturadesussubrbolesdifierealomsen1. Estasimplerestriccinhacequeunrboldennodostenga alturamximaO(logn)
NotaHistrica
ElnombreAVLesenhonoradosmatemticosrusos,G.M.Adelson Vel`skiiyE.M.Landis,quienesidearonelmtodoen1962.
rboles AVL
EjemplosderbolesAVL
rboles AVL
EjemplosderbolesnoAVL
rboles AVL
Factordeequilibrio
Paracadanododelrbolsedefinesufactordeequilibrio:
fe(x)=alturasubrbolderechodexalturasubrbolizquierdodex
rboles AVL
Factordeequilibrio
Cuandounnuevoelementoseinserta,elfactordeequilibriode sunodoseinicializaen0 Despusdecadainsercinhabrquerevisarqueelfactorde equilibriodelosnodosinvolucrados(losqueestnenelcaminodesdelaraz hastaelpadredelnodoinsertado,elrestonopuedecambiardealtura)nosehaya daado Encasodedaarseelfactordeequilibriodeunnodo,tendremos quereestructurarelrbol
rboles AVL
f.e.=2 f.e.=1 f.e.=0
desequilibrioaladerecha
desequilibrioalaizquierda
rboles AVL
desequilibrioaladerecha desequilibrioalaizquierda
f.e.=2 f.e.=1
f.e.=0
rboles AVL
RotacionesenunAVL
Despusdeunainsercinoborrado,sielfactordeequilibriode algunodelosnodosinvolucradoses2o2hayquerealizaruna correccindeste Estoselogramedianterotaciones
Unasecuenciadeintercambiodepunterosenelrbolpara recuperarelequilibriodelrbol
Unhechomuyimportantedeestasrotaciones,esquesemantiene elordenamientodelrbol
sielrboloriginaleraABB,elresultadotambinloseguirsiendo
rboles AVL
Rotacionessimples
Sidespusdeunainsercin/borradounnodoestdesequilibradoala izquierda(fe=2),ysuhijoizquierdotieneelmismosigno(),se corrigeconunarotacinsimplealaderecha. f.e.=2 f.e.=1
7 f.e.=0 2 9
rboles AVL
Rotacionessimples
Sidespusdeunainsercin/borradounnodoestdesequilibradoala izquierda(fe=2),ysuhijoderechotieneelmismosigno(+),secorrige conunarotacinsimplealaizquierda.
2 f.e.=2 7
f.e.=1
7 f.e.=0 2 9
rboles AVL
Rotacionesdobles
Sielnodoestdesequilibradoalaizquierda(FE=2),ysuhijo izquierdotienedistintosigno(+)hacerrotacindobleizquierda derecha.
f.e. = -2 f.e. = 1
3
f.e. = -2 f.e. = -1
5
f.e. = 0
5
5 3 8
f.e. = 0
rboles AVL
Rotacionesdobles
Sielnodoestdesequilibradoaladerecha(FE=2),ysuhijoderecho tienedistintosigno()hacerrotacindoblederechaizquierda.
f.e. = 2
f.e. = 2
f.e. = 0
10
f.e. = -1
13
f.e. = 1
10 8 13
10
13
rboles AVL
InsercinenunAVL
Sehaceunainsercinounaeliminacinsegnelmtodo tradicionaldelABB. Posteriormentesedeberanalizarsisehaproducidoun desbalance. Msalldequepuedenservarioslosnodosdesbalanceados,hay quepreocuparsedelltimonodoenelcaminodeinsercinquese encuentredesbalanceado Siesas,aplicarlasrotacionescorrespondientespararestaurarlo.
rboles AVL
InsercinenunAVL
Caso 1:
Resultado :
10
10
Input : 17
5 15 15 17
rboles AVL
InsercinenunAVL
Caso 2:
Input : 18
10
5
10
15
15
12 16
12
16
18
Se produce desbalance en el subrbol derecho externo: se debe sigue hacer una rotacin simple a la izquierda.
rboles AVL
InsercinenunAVL
10
Resultado :
15
10
16
12
18
12
nodoAVL*rotIzq(nodoAVL*a){ nodoAVL*temp=a>der;
18
rboles AVL
InsercinenunAVL
a
10 5 12 temp
15 16 18
rboles AVL
InsercinenunAVL
a
10 5 12 temp
15 16 18
rboles AVL
InsercinenunAVL
a
10 5 12 temp
15 16 18
rboles AVL
InsercinenunAVL
temp
15
10
16
12
18
rboles AVL
InsercinenunAVL
Caso 3: 10
Input : 4
5
10
15
15 2 6
6 4
Se produce desbalance en el subrbol izquierdo externo: se debe hacer una rotacin simple a la derecha. sigue
rboles AVL
InsercinenunAVL
10
10
15
rboles AVL
InsercinenunAVL
Caso 4: 10 5 5 15 2 12 16 4 6 15
Input : 13
10
Se produce desbalance en el subrbol derecho interno: se debe hacer una rotacin doble derecha-izquierda. sigue
rboles AVL
10
InsercinenunAVL
10
12 15
15 13 12 13 16 12 16
10
15
13
16
rboles AVL
InsercinenunAVL
Caso 5: 10
Input : 8
10
15
15
Se produce desbalance en el subrbol izquierdo interno: se debe hacer una rotacin doble izquierda-derecha.
sigue
rboles AVL
10
InsercinenunAVL
10 5 2 2 6 6 8
NodoAVL*rotIzqDer(nodoAVL*a){ a>izq=rotIzq(a>izq); returnrotDer(a); }
6 8
15
15
10
15
rboles AVL
InsercinenunAVL
Ejercicio InsertarenunrbolAVL(inicialmentevaco)lasiguiente secuenciadenmerosenteros: S={100,60,40,120,140,110,114,116} Dibujelasecuenciadeinsercindecadaelementoylas respectivasrotacionesqueseanecesariorealizar.
rboles AVL
EliminacinenunAVL
Nosiempreelresultadodeeliminarunnododarcomoresultado unrbolAVL SisepierdelacondicinAVL,sedeberrestaurarelfactorde equilibrio,delamismamaneraqueconlasinserciones
Porejemplo,Colasdeprioridad:
Elementoslleganalsistemaconciertaprioridad,yencadamomentose atiendealelementodemayorprioridad Llegadasdepacientesenfermosaserviciodeurgencia,ollegadade procesosaserejecutadosporunsistemaoperativo
EstudiaremosacontinuacinelTDAColadePrioridad
Permitebuscarporelelementodemximaprioridad,ascomoinsertar elementosarbitrariosyeliminarelelementodemximaprioridad
voidinitColaP(tColaP*P)
//eliminatodosloselementosdeunacoladeprioridad,dejndolavaca
voidclearColaP(tColaP*P);
//encuentraelmximoelementodelconjunto
tipoElemfindMax(tColaP*P);
//cantidaddeelementosenlacoladeprioridad
intsizeColaP(tColaP*P)
//eliminaelmximoelementodelconjunto
voidremoveMax(tColaP*P);
//insertaunelementoitemenlacoladeprioridad
voidinsertColaP(tCola*P,tipoElemitem);
Listasordenadasbasadasenarreglos:lainsercinesO(n)porqueel
arreglodebemantenerseordenado.Elmximosepuedeencontrarentiempo O(1).BorradoentiempoO(1)
rbolesAVL:BuscarelmximotomatiempoO(logn),insercinyborrado
tomatiempoO(logn)
65
73
53
15
68
49
Noesheap (noescasilleno):
80
15
73
65 49
73
53
80
68
53
68
49
15
tipoElemfindMax(tColaP*P);
voidinsertColaP(tCola*P,tipoElemitem);
11
12
11
20
11 11 15 20 12 20
15
15
12
11 15 5 12
flotar
11 5 20 15 12
flotar
5 11 12 15
20
16
5 11 12 15 16
5 11 20 15 16 12 8
flotar
5 11 20 15 16 8 12
20
voidremoveMax(tColaP*P);
Enunheap,elelementoqueseeliminaeslaraz:eldemayorprioridad
Algoritmo
1. Sesustituyeelelementoedelaltimahojaconeldelarazyse eliminalahoja 2. Sehundeelelementoe.Mientraseseamayorquealgunode sushijos,seintercambiaconelmenordesushijos.
12 8 12 20 11 15 16 8 5
11 20
15
16
12 11 20 15
8 11 20 15 16 12
16
ir nd hu
47
22
4 8 16
32 9 3
44
6 12 9
12
19
10 11 41 37
Senecesitamantenerunnmeroenteroqueindiquecuntos nodoshayactualmenteenelrbol(porcinusadadelarreglo)
3
9
37 41
10 11
9
12 13 14
47
22
4 8 16
32 9 3
44
6 12 9
12
19
Esta representacin permite ahorrar el espacio de los punteros, lo que en muchas aplicaciones puede ser relevante
10 11 41 37
rboles 2-3
Muchasaplicacionesnecesitanmanipularmuygrandes volmenesdedatos,delordendevariosterabytes Enesoscasos,losdatosdebenseralmacenadosendisco,y recuperadosamemoriaprincipalparabuscar
Ejemplos
Basesdedatosdegrandescompaas(porej.,supermercados) Facebook,twitter,redessocialesengeneral BuscadoresWeb(google,Yahoo!,Bing,etc.) Etc.
rboles 2-3
Parasoportarbsquedaseficientessobreesosconjuntosdedatos, podramosemplearlosABByavistos,oinclusolosAVL Habraquealmacenarlosendisco,ycargarlaspartesdelrbolque sonconsultadasduranteunabsqueda Sinembargo,almacenarunaestructuradedatosendiscorequiere anlisisextra
Elaccesoadiscoesdelordendelos10milisegundos AccederaunaceldadememoriaSDRSDRAMde133MHztoma 10nanosegundos=0.00001milisegundos(1millndevecesmslento) Analoga:necesitaralgoytomarlodesdeelescritorio(2segundos)versus irabuscarloaChinaenbarco(24das)
rboles 2-3
Sisuponemosunabasededatosconn=1.000millonesde elementos,ydadoqueunrbolAVLnecesitaO(logn)accesos,esto significa30accesosadiscoenelpeorcasoparabuscar Estoesporquelosrbolessonbinarios,yporendeloslogaritmos sonenbase2 Esestapartedelcursoestudiaremosrepresentacionesderbolesque sondeordenmayora2,porendepermitenreducirlacantidadde accesosadisco
Porejemplo,sielrbolesdeorden10,lacantidaddeaccesosparael ejemplosereducea9,mientrasquesielordendelrboles100,sebajaa 4.5accesos (Esoesmuchomsabordablerespectodenmerodeaccesosadisco)
rboles 2-3
Unrbol23esunrbolordenadodefinidocomo
Cadanodopuedealmacenar2o3elementos Cadanodointernotiene2hijos(sialmacenaunelemento)o3hijos (sialmacena2elementos) Todaslashojasseencuentraenelmismoniveldelrbol,porendeel rbolesbalanceado
rboles 2-3
rboles 2-3
Bsquedaenunrbol23
Desdelarazsebajahastaencontrareldatoollegaraunahoja
Elcaminoaseguirvienedadoporlacomparacinentreeldato buscadoyelcontenidodelnodoinspeccionadoencada momento Sisellegaaunsubrbolvaco,eldatonoestenelrbol Sinoestvaco,primerobuscarenlarazdelsubrbolactual Siesalgunodeloselementosdelarazdelsubrbolactual,se encontr Sino,sielnodoesunahojayelelementonoestenelnodo, finalizar
rboles 2-3
Bsquedaenunrbol23
Sielnodonoesunahoja Sislohayunelementoenelnodo: Siesmayorqueeldatoabuscar,sesigueporelhijo derecho Siesmenor,sesigueporelhijoizquierdo. Sienelnodohaydoselementos,r1yr2(conr1r2): Sieldatoesmenorquer1,buscarporelhijoizquierdo. Sieldatoesmayorquer1ymenorquer2,buscarporel hijocentral. Siesmayorquer2buscarporelhijoderecho.
rboles 2-3
Insercinenunrbol23
AligualqueenlosABByAVL,lainsercindenuevos elementosocurrealniveldelashojas Comoenlosrbolesbinariosdebsqueda,elprimerpaso consisteenlocalizarelnodohojaendondedebeirelelemento Sinembargo,ahoraelcrecimientodelrboleshacialaraz
Estogarantizaquelashojasestnsiempreenelmismoniveldel rbol,loqueasuvezgarantizaelbalancedelrbol
rboles 2-3
Insercinenunrbol23
Lasinsercionesenunrbol23tienendoscasos 1. Hayespacioenelnodopueshayunsloelemento 2. Nohayespacioyelnododebedividirseendosylamediana delostreselementosseinsertaenelpadrerecursivamente. Estopuedegenerarunasecuenciadedivisioneshastalaraz
rboles 2-3
Insercinenunrbol23
Entodosloscasos,elelementoainsertarsedenotaporx
Nodo hoja Nodo hoja luego de la insercin
Caso 1:
r1
r1 < x
r1
Nodo hoja
Caso 2:
r1
x < r1
r1
rboles 2-3
Insercinenunrbol23
Entodosloscasos,elelementoainsertarsedenotaporx Caso 3: r1 r2 x > r2 Sube r2 x
r1
r2
r1
rboles 2-3
Insercinenunrbol23
Entodosloscasos,elelementoainsertarsedenotaporx Caso 4: r1 r2 x < r1 Sube r1 x r1 r2
r2
rboles 2-3
Insercinenunrbol23
Entodosloscasos,elelementoainsertarsedenotaporx Caso 5: r1 r2 r1 < x < r2 Sube x r2
r1
r1
r2
rboles 2-3
Ejemplodeinsercinenunrbol23
Insertar en un rbol2-3 inicialmante vaco los siguientes elementos S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 }
30
30
30
15 2
15
30
30
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 63
15 2
30
63
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 65
15 Sube el 63 2 30 63 65 2 30 65 15 63
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 1
15
63
30
65
rboles 2-3
S={ 30, 2, 15, 63, 65, 1, 0, 14, 27, 8, 9, 81, 79, 60 } Input: 0
Sube el 1 0 1 2 15 63 1 15 63
30
65
2 15 1
30
65
Sube el 15 1 15 63
63
30
65
30
65
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 14 15
1 63
14 15
30
65
Input: 27
1
63
14
27 30
65
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 8
15 1 Sube el 8 0 2 8 14 27 30 65 15 1 8 63 63
14
27 30
65
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 9
1 8 15 63
14
27 30 15
65
Input: 81
1 8
63
14
27 30
65 81
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60 } Input: 79 15
1 8 63 Sube el 79 65 79 15 81
14
27 30
63
79
14
27 30
65
81
rboles 2-3
S={ 30, 2, 15, 63, 65, 1,0, 14, 27, 8, 9, 81, 79, 60} Input: 60
15 63
30
79
14
27
60
65
81
rboles 2-3
Borradoenunrbol23
Losborradosenunrbol23sondemasiadocomplejos PostponemossuestudioparaelcasodelosrbolesB
rboles 2-3
ImplementacindeltipotArbol23enC
typedefstructnodoA23{ tipoElemelem1,elem2; structnodoA23*izq,*cent,*der; }nodoArbol23; typedefstruct{ nodoArbol23*raiz; intnElem; }tArbol23;
rboles 2-3
Anlisisdelaalturadeunrbol23
Enelpeorcaso,tenemosunrbolbinariocompleto,porlotanto tenemosque n=1+2+4+...+2(h1)=(2h1)/(21)=2h1nodos Esdecirh<=log2(n+1) Enelmejorcasoesunrbolternario,entonces: n=1+3+9+...+3(h1)=(3h1)/(31)=(3h1)/2nodos Esdecirh>=log3(2n+1) Luegolaalturadeunrbol23estentrelog2(n)ylog3(n)
Bibliografa
Data Structures and Algorithm Analysis. Clifford A. Shaffer.
http://people.cs.vt.edu/~shaffer/Book/C++3e20120605.pdf
Ver Captulos 5, 10.3, 10.4, 13.2.1. Estructuras de Datos y Algoritmos. Aho, Hopcroft y Ullman. Addison-Wesley, 1998. Introduction to Algorithms. Cormen, Leiserson, Rivest y Stein. 3. ed. MIT Press 2009: I-XIX, 1-1292