1. Arboles Binarios
Ing. Juan Ignacio Zamora M. MS.c
Facultad de Ingenierías
Licenciatura en Ingeniería Informática con Énfasis en Desarrollo de Software
Universidad Latinoamericana de Ciencia y Tecnología
2. Un Árbol Binario
¡ Es una estructura de datos de forma arbórea en
la cual cada nodo puede tener hasta 2 nodos
subordinados
¡ Se dice que cada nodo puede tener otros nodos a
la izquierda y a la derecha
¡ Usualmente utilizada como un diccionario o
como una cola de prioridad.
¡ El tiempo de la mayor parte de las operaciones
de un árbol están sujetas a la altura del mismo
(normalmente O(lg n) en el peor caso)
12.1 What is a binary search tree? 287
5
2 5
5
8
7
6
(a)
6 8
7
5
2
(b)
3. Mas sobre Arboles Binarios…
¡ El nodo padre es el único nodo cuyo padre no
esta definido << es nulo >>
¡ Los arboles Binarios de Búsqueda se definen por
el “Binary Search Property”
¡ Sea “x” un nodo es un árbol binario de búsqueda. Si
“y” es un nodo en el sub arbol izquierdo de “x”,
entonces y.key <= x.key. Si “y” es un nodo en el sub
arbol derecho de “x” entones y.key >= x.key
12.1 What is a binary search tree?
2 5
5
8
7
6
4. Mas sobre Arboles Binarios…
¡ Para imprimir los elementos de un árbol de forma
ordenada se aplica un algoritmo que se llama “En-
Orden” o “Inorder-Tree-Walk” à O(n)
¡ “Pre-Orden” imprime primero el nodo { x.key }
¡ “Post-Orden” imprime el nodo de ultimo
288 Chapter 12 Binary Search Trees
INORDER-TREE-WALK.x/
1 if x ¤ NIL
2 INORDER-TREE-WALK.x:left/
3 print x:key
4 INORDER-TREE-WALK.x:right/
As an example, the inorder tree walk prints the keys in each of the two binary
search trees from Figure 12.1 in the order 2; 5; 5; 6; 7; 8. The correctness of the
algorithm follows by induction directly from the binary-search-tree property.
It takes ‚.n/ time to walk an n-node binary search tree, since after the ini-
tial call, the procedure calls itself recursively exactly twice for each node in the
tree—once for its left child and once for its right child. The following theorem
gives a formal proof that it takes linear time to perform an inorder tree walk.
5. Ejercicio
A = {1, 4, 5, 10, 16, 17, 21}
1. Construya un árbol del altura 2
2. Construya un árbol de altura 4
7. Búsqueda
¡ Si el árbol cumple con “la propiedad”, solo se
debe escoger el camino correcto…Chapter 12 Binary Search Trees
2 4
3
13
7
6
17 20
18
15
9
Figure 12.2 Queries on a binary search tree. To search for the key 13 in the tree, we follow the path
15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by following
left pointers from the root. The maximum key 20 is found by following right pointers from the root.
The successor of the node with key 15 is the node with key 17, since it is the minimum key in the
2 4
3
13
17 20
9
Figure 12.2 Queries on a binary search tree. To search for the k
15 ! 6 ! 7 ! 13 from the root. The minimum key in the tre
left pointers from the root. The maximum key 20 is found by fol
The successor of the node with key 15 is the node with key 17,
right subtree of 15. The node with key 13 has no right subtree,
ancestor whose left child is also an ancestor. In this case, the nod
TREE-SEARCH.x; k/
1 if x == NIL or k == x:key
2 return x
3 if k < x:key
4 return TREE-SEARCH.x:left; k/
5 else return TREE-SEARCH.x:right; k/
The procedure begins its search at the root and trace
the tree, as shown in Figure 12.2. For each node x i
key k with x:key. If the two keys are equal, the searc
than x:key, the search continues in the left subtree o
tree property implies that k could not be stored in the
if k is larger than x:key, the search continues in th
El “Tree-Search” puede ser
implementado con un for loop en
lugar de usar recursividad
12.2 Querying a binary search tree 291
ITERATIVE-TREE-SEARCH.x; k/
1 while x ¤ NIL and k ¤ x:key
2 if k < x:key
3 x D x:left
4 else x D x:right
5 return x
8. Máximo y Mínimo
¡ El mínimo se trae el nodo mas pequeño del
árbol. Solamente sigue el camino izquierdo para
encontrarlo…
¡ El Máximo funciona de forma inversa y se va por
el lado derecho del árbol hasta encontrar el
valor máximo en el extremo derecho.
¡ Ambos tienen un tiempo de O(h)
5 return x
Minimum and maximum
We can always find an ele
following left child pointe
Figure 12.2. The followin
the subtree rooted at a giv
TREE-MINIMUM.x/
1 while x:left ¤ NIL
2 x D x:left
3 return x
The binary-search-tree pr
node x has no left subtree,
large as x:key, the minim
a left subtree, then since n
key in the left subtree is
rooted at x resides in the
The pseudocode for TR
TREE-MAXIMUM.x/
1 while x:right ¤ NIL
2 x D x:right
3 return x
Both of these procedures
SEARCH, the sequence of
the subtree rooted at a give
TREE-MINIMUM.x/
1 while x:left ¤ NIL
2 x D x:left
3 return x
The binary-search-tree pro
node x has no left subtree,
large as x:key, the minimu
a left subtree, then since no
key in the left subtree is n
rooted at x resides in the s
The pseudocode for TRE
TREE-MAXIMUM.x/
1 while x:right ¤ NIL
2 x D x:right
3 return x
Both of these procedures r
SEARCH, the sequence of
the root.
Successor and predecesso
Given a node in a binary
the sorted order determine
290 Chapter 12 Binary Search Trees
2 4
3
13
7
6
17 20
18
15
9
9. Sucesor y Predecesor
¡ El sucesor de un nodo “x” es el nodo con la llave
menor a “x.key”.
¡ El algoritmo obtiene el valor si siquiera comparar
valores… claro si el árbol cumple con
propiedad…
292 Chapter 12 Binary Search Trees
successor of a node x is the node with the smalle
structure of a binary search tree allows us to dete
without ever comparing keys. The following proce
node x in a binary search tree if it exists, and NIL
tree:
TREE-SUCCESSOR.x/
1 if x:right ¤ NIL
2 return TREE-MINIMUM.x:right/
3 y D x:p
4 while y ¤ NIL and x == y:right
5 x D y
6 y D y:p
7 return y
Chapter 12 Binary Search Trees
2 4
3
13
7
6
17 20
18
15
9
Figure 12.2 Queries on a binary search tree. To search for the key 13 in the tree, we follow the path
10. Inserción
¡ Tanto eliminar como agregar elementos
transforma el árbol. Por tanto es importante que
dichas operaciones ayuden a soportar la
propiedad“Binary-Search-Tree”.
¡ El Algoritmo de Insertar, toma un nodo “z” para el
cual z.key = v y z.left = NULL, z.right = NULL y
modifica el árbol “T” y algunas propiedades de
“z” con la intención de insertarlo en el lugar
correcto.
12.3 Insertion and deletion
2 9
5
13 17
15 19
18
12
11. Inserción
12.3 Insertion and deletion
2 9
5
13 17
15 19
18
12
forward, but handling deletion is somewhat more intricate.
Insertion
To insert a new value into a binary search tree T , we use the procedure TREE-
INSERT. The procedure takes a node ´ for which ´:key D , ´:left D NIL,
and ´:right D NIL. It modifies T and some of the attributes of ´ in such a way that
it inserts ´ into an appropriate position in the tree.
TREE-INSERT.T; ´/
1 y D NIL
2 x D T:root
3 while x ¤ NIL
4 y D x
5 if ´:key < x:key
6 x D x:left
7 else x D x:right
8 ´:p D y
9 if y == NIL
10 T:root D ´ // tree T was empty
11 elseif ´:key < y:key
12 y:left D ´
13 else y:right D ´
A donde se Inserta 14?...
12. Coding-Time (Grupal)
¡ Cree una clase que se llame “UlacitTree” o “Utree”
¡ Cree una clase Nodo UNode que contenga
¡ Una valor entero “Key”
¡ Una variable tipo UNode Right, Left y Parent o P.
¡ Para la clase “UTree”
¡ Desarrolle todos los métodos expuestos hasta el momento y según la
definición de esta presentación!!!
¡ Buscar, Mínimo, Máximo, Sucesor e Insertar
¡ Sobrecargue el método ToString() para que imprima lo que tenga el
árbol en una lista delimitada por comas “1,4,6,8,9,14,16”
¡ Este código será usado la próxima semana para programar las
eliminaciones.
¡ Este Código debe ser entregado en el foro respectivo y cuenta como
Tarea
13. Eliminar
Eliminar o “podar” un elemento “z” de un árbol tiene 3 implicaciones
principales
Si “z” no tiene hijos… simplemente se elimina y se reemplaza con un
valor nulo {null}
Si “z” tiene 1 hijo, entonces este hijo toma la posición de “z” y se
elimina
Si “z” tiene 2 hijos, entonces debemos encontrar el sucesor “y” el cual
debe estar en el sub arbol derecho…
• “y” toma la posición de “z”
• El resto del sub árbol original de “z” se convierte en la rama derecha de “y” & de igual
forma el sub árbol izquierdo de “z” se convierte en el árbol izquierdo de “y”
Para mover sub-arboles en la misma estructura se utiliza el método
“Trasplantar”; el cual reemplaza un sub-árbol por otro desde su raíz.
child alone.
Otherwise, y lies w
In this case, we first
by y.
In order to move subtr
subroutine TRANSPLANT,
another subtree. When T
the subtree rooted at node
parent ends up having as
TRANSPLANT.T; u; /
1 if u:p == NIL
2 T:root D
3 elseif u == u:p:left
4 u:p:left D
5 else u:p:right D
6 if ¤ NIL
7 :p D u:p
Lines 1–2 handle the case
child or a right child of it
is a left child, and line 5 u
NIL, and lines 6–7 update
attempt to update :left an
of TRANSPLANT’s caller.
14. qq
z(a) r
qq
z
l
(b)
q
z
l
(c)
q
y
ly
q
z
l
(d)
r
q
z
l r
y
q
l r
y
r
l
x
x
xy
x
x
NIL
NIL
NIL
NIL
NIL
qq
z(a) r
qq
z
l
(b)
q
z
l
(c)
q
y
ly
q
z
l
(d)
r
q
z
l r
y
q
l r
y
r
l
x
x
xy
x
x
NIL
NIL
NIL
NIL
NIL
node ´ from binary search tree T :
TREE-DELETE.T; ´/
1 if ´:left == NIL
2 TRANSPLANT.T; ´; ´:right/
3 elseif ´:right == NIL
4 TRANSPLANT.T; ´; ´:left/
5 else y D TREE-MINIMUM.´:right/
6 if y:p ¤ ´
7 TRANSPLANT.T; y; y:right/
8 y:right D ´:right
9 y:right:p D y
10 TRANSPLANT.T; ´; y/
11 y:left D ´:left
12 y:left:p D y
The TREE-DELETE procedure executes the fo
handle the case in which node ´ has no left child,
which ´ has a left child but no right child. Lines 5
cases, in which ´ has two children. Line 5 finds
of ´. Because ´ has a nonempty right subtree, its
that subtree with the smallest key; hence the call to
we noted before, y has no left child. We want to sp
and it should replace ´ in the tree. If y is ´’s right c
as a child of its parent by y and replace y’s left
a
b
y
Si “y” es el hijo
derecho de
“z”
c
d
15. Ejercicio:
2 9
5
13 17
15 19
18
12
Figure 12.3 Inserting an item with key 13 into a binary search tree
the simple path from the root down to the position where the item
indicates the link in the tree that is added to insert the item.
Figure 12.3 shows how TREE-INSERT works. Just li
Desarrolle los métodos “Transplant” & “Tree-Delete” sobre el código
de la semana anterior.
Cree el árbol mostrado en la parte superior.
1. Elimine primero el nodo z.v = 18 e imprima el arbo “en orden”
2. Elimine el nodo z.v = 12 e imprima en orden.