+ All Categories
Home > Education > Arboles Binarios

Arboles Binarios

Date post: 17-Jul-2015
Category:
Upload: juan-zamora-msc-mba
View: 47 times
Download: 2 times
Share this document with a friend
15
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
Transcript

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

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)

Figure 12.1 Binary search trees. For any node x, the keys in the left subtree of x are at most x:key,and the keys in the right subtree of x are at least x:key. Different binary search trees can representthe same set of values. The worst-case running time for most search-tree operations is proportionalto the height of the tree. (a) A binary search tree on 6 nodes with height 2. (b) A less efficient binarysearch tree with height 4 that contains the same keys.

its right child, and its parent, respectively. If a child or the parent is missing, theappropriate attribute contains the value NIL. The root node is the only node in thetree whose parent is NIL.

The keys in a binary search tree are always stored in such a way as to satisfy thebinary-search-tree property:

Let x be a node in a binary search tree. If y is a node in the left subtreeof x, then y:key ! x:key. If y is a node in the right subtree of x, theny:key " x:key.

Thus, in Figure 12.1(a), the key of the root is 6, the keys 2, 5, and 5 in its leftsubtree are no larger than 6, and the keys 7 and 8 in its right subtree are no smallerthan 6. The same property holds for every node in the tree. For example, the key 5in the root’s left child is no smaller than the key 2 in that node’s left subtree and nolarger than the key 5 in the right subtree.

The binary-search-tree property allows us to print out all the keys in a binarysearch tree in sorted order by a simple recursive algorithm, called an inorder treewalk. This algorithm is so named because it prints the key of the root of a subtreebetween printing the values in its left subtree and printing those in its right subtree.(Similarly, a preorder tree walk prints the root before the values in either subtree,and a postorder tree walk prints the root after the values in its subtrees.) To usethe following procedure to print all the elements in a binary search tree T , we callINORDER-TREE-WALK.T:root/.

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? 287

5

2 5

5

8

7

6

(a)

6 8

7

5

2

(b)

Figure 12.1 Binary search trees. For any node x, the keys in the left subtree of x are at most x:key,and the keys in the right subtree of x are at least x:key. Different binary search trees can representthe same set of values. The worst-case running time for most search-tree operations is proportionalto the height of the tree. (a) A binary search tree on 6 nodes with height 2. (b) A less efficient binarysearch tree with height 4 that contains the same keys.

its right child, and its parent, respectively. If a child or the parent is missing, theappropriate attribute contains the value NIL. The root node is the only node in thetree whose parent is NIL.

The keys in a binary search tree are always stored in such a way as to satisfy thebinary-search-tree property:

Let x be a node in a binary search tree. If y is a node in the left subtreeof x, then y:key ! x:key. If y is a node in the right subtree of x, theny:key " x:key.

Thus, in Figure 12.1(a), the key of the root is 6, the keys 2, 5, and 5 in its leftsubtree are no larger than 6, and the keys 7 and 8 in its right subtree are no smallerthan 6. The same property holds for every node in the tree. For example, the key 5in the root’s left child is no smaller than the key 2 in that node’s left subtree and nolarger than the key 5 in the right subtree.

The binary-search-tree property allows us to print out all the keys in a binarysearch tree in sorted order by a simple recursive algorithm, called an inorder treewalk. This algorithm is so named because it prints the key of the root of a subtreebetween printing the values in its left subtree and printing those in its right subtree.(Similarly, a preorder tree walk prints the root before the values in either subtree,and a postorder tree walk prints the root after the values in its subtrees.) To usethe following procedure to print all the elements in a binary search tree T , we callINORDER-TREE-WALK.T:root/.

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 ¤ NIL2 INORDER-TREE-WALK.x: left/3 print x:key4 INORDER-TREE-WALK.x:right/

As an example, the inorder tree walk prints the keys in each of the two binarysearch trees from Figure 12.1 in the order 2; 5; 5; 6; 7; 8. The correctness of thealgorithm 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 thetree—once for its left child and once for its right child. The following theoremgives a formal proof that it takes linear time to perform an inorder tree walk.

Theorem 12.1If x is the root of an n-node subtree, then the call INORDER-TREE-WALK.x/takes ‚.n/ time.

Proof Let T .n/ denote the time taken by INORDER-TREE-WALK when it iscalled on the root of an n-node subtree. Since INORDER-TREE-WALK visits all nnodes of the subtree, we have T .n/ D !.n/. It remains to show that T .n/ D O.n/.

Since INORDER-TREE-WALK takes a small, constant amount of time on anempty subtree (for the test x ¤ NIL), we have T .0/ D c for some constant c > 0.

For n > 0, suppose that INORDER-TREE-WALK is called on a node x whoseleft subtree has k nodes and whose right subtree has n ! k ! 1 nodes. The time toperform INORDER-TREE-WALK.x/ is bounded by T .n/ " T .k/CT .n!k!1/Cdfor some constant d > 0 that reflects an upper bound on the time to execute thebody of INORDER-TREE-WALK.x/, exclusive of the time spent in recursive calls.

We use the substitution method to show that T .n/ D O.n/ by proving thatT .n/ " .cCd/nC c. For n D 0, we have .cCd/ #0C c D c D T .0/. For n > 0,we haveT .n/ " T .k/C T .n ! k ! 1/C d

D ..c C d/k C c/C ..c C d/.n ! k ! 1/C c/C d

D .c C d/nC c ! .c C d/C c C d

D .c C d/nC c ;

which completes the proof.

Ejercicio A = {1, 4, 5, 10, 16, 17, 21} 1.  Construya un árbol del altura 2 2.  Construya un árbol de altura 4

+ Operaciones ¡ Algunas operaciones comunes à O(h) ¡  Búsqueda

¡  Máximo

¡  Mínimo

¡  Sucesor

¡  Predecesor

¡  Mas… ???

¡  Inserciones

¡  Eliminación ( y Compresión del Árbol)

Búsqueda ¡  Si el árbol cumple con “la propiedad”, solo se

debe escoger el camino correcto… 290 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 path15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by followingleft 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 theright subtree of 15. The node with key 13 has no right subtree, and thus its successor is its lowestancestor whose left child is also an ancestor. In this case, the node with key 15 is its successor.

TREE-SEARCH.x; k/

1 if x == NIL or k == x:key2 return x3 if k < x:key4 return TREE-SEARCH.x: left; k/5 else return TREE-SEARCH.x:right; k/

The procedure begins its search at the root and traces a simple path downward inthe tree, as shown in Figure 12.2. For each node x it encounters, it compares thekey k with x:key. If the two keys are equal, the search terminates. If k is smallerthan x:key, the search continues in the left subtree of x, since the binary-search-tree property implies that k could not be stored in the right subtree. Symmetrically,if k is larger than x:key, the search continues in the right subtree. The nodesencountered during the recursion form a simple path downward from the root ofthe tree, and thus the running time of TREE-SEARCH is O.h/, where h is the heightof the tree.

We can rewrite this procedure in an iterative fashion by “unrolling” the recursioninto a while loop. On most computers, the iterative version is more efficient.

290 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 path15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by followingleft 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 theright subtree of 15. The node with key 13 has no right subtree, and thus its successor is its lowestancestor whose left child is also an ancestor. In this case, the node with key 15 is its successor.

TREE-SEARCH.x; k/

1 if x == NIL or k == x:key2 return x3 if k < x:key4 return TREE-SEARCH.x: left; k/5 else return TREE-SEARCH.x:right; k/

The procedure begins its search at the root and traces a simple path downward inthe tree, as shown in Figure 12.2. For each node x it encounters, it compares thekey k with x:key. If the two keys are equal, the search terminates. If k is smallerthan x:key, the search continues in the left subtree of x, since the binary-search-tree property implies that k could not be stored in the right subtree. Symmetrically,if k is larger than x:key, the search continues in the right subtree. The nodesencountered during the recursion form a simple path downward from the root ofthe tree, and thus the running time of TREE-SEARCH is O.h/, where h is the heightof the tree.

We can rewrite this procedure in an iterative fashion by “unrolling” the recursioninto a while loop. On most computers, the iterative version is more efficient.

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:key2 if k < x:key3 x D x: left4 else x D x:right5 return x

Minimum and maximumWe can always find an element in a binary search tree whose key is a minimum byfollowing left child pointers from the root until we encounter a NIL, as shown inFigure 12.2. The following procedure returns a pointer to the minimum element inthe subtree rooted at a given node x, which we assume to be non-NIL:

TREE-MINIMUM.x/

1 while x: left ¤ NIL2 x D x: left3 return x

The binary-search-tree property guarantees that TREE-MINIMUM is correct. If anode x has no left subtree, then since every key in the right subtree of x is at least aslarge as x:key, the minimum key in the subtree rooted at x is x:key. If node x hasa left subtree, then since no key in the right subtree is smaller than x:key and everykey in the left subtree is not larger than x:key, the minimum key in the subtreerooted at x resides in the subtree rooted at x: left.

The pseudocode for TREE-MAXIMUM is symmetric:

TREE-MAXIMUM.x/

1 while x:right ¤ NIL2 x D x:right3 return x

Both of these procedures run in O.h/ time on a tree of height h since, as in TREE-SEARCH, the sequence of nodes encountered forms a simple path downward fromthe root.

Successor and predecessorGiven a node in a binary search tree, sometimes we need to find its successor inthe sorted order determined by an inorder tree walk. If all keys are distinct, the

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)

12.2 Querying a binary search tree 291

ITERATIVE-TREE-SEARCH.x; k/

1 while x ¤ NIL and k ¤ x:key2 if k < x:key3 x D x: left4 else x D x:right5 return x

Minimum and maximumWe can always find an element in a binary search tree whose key is a minimum byfollowing left child pointers from the root until we encounter a NIL, as shown inFigure 12.2. The following procedure returns a pointer to the minimum element inthe subtree rooted at a given node x, which we assume to be non-NIL:

TREE-MINIMUM.x/

1 while x: left ¤ NIL2 x D x: left3 return x

The binary-search-tree property guarantees that TREE-MINIMUM is correct. If anode x has no left subtree, then since every key in the right subtree of x is at least aslarge as x:key, the minimum key in the subtree rooted at x is x:key. If node x hasa left subtree, then since no key in the right subtree is smaller than x:key and everykey in the left subtree is not larger than x:key, the minimum key in the subtreerooted at x resides in the subtree rooted at x: left.

The pseudocode for TREE-MAXIMUM is symmetric:

TREE-MAXIMUM.x/

1 while x:right ¤ NIL2 x D x:right3 return x

Both of these procedures run in O.h/ time on a tree of height h since, as in TREE-SEARCH, the sequence of nodes encountered forms a simple path downward fromthe root.

Successor and predecessorGiven a node in a binary search tree, sometimes we need to find its successor inthe sorted order determined by an inorder tree walk. If all keys are distinct, the

12.2 Querying a binary search tree 291

ITERATIVE-TREE-SEARCH.x; k/

1 while x ¤ NIL and k ¤ x:key2 if k < x:key3 x D x: left4 else x D x:right5 return x

Minimum and maximumWe can always find an element in a binary search tree whose key is a minimum byfollowing left child pointers from the root until we encounter a NIL, as shown inFigure 12.2. The following procedure returns a pointer to the minimum element inthe subtree rooted at a given node x, which we assume to be non-NIL:

TREE-MINIMUM.x/

1 while x: left ¤ NIL2 x D x: left3 return x

The binary-search-tree property guarantees that TREE-MINIMUM is correct. If anode x has no left subtree, then since every key in the right subtree of x is at least aslarge as x:key, the minimum key in the subtree rooted at x is x:key. If node x hasa left subtree, then since no key in the right subtree is smaller than x:key and everykey in the left subtree is not larger than x:key, the minimum key in the subtreerooted at x resides in the subtree rooted at x: left.

The pseudocode for TREE-MAXIMUM is symmetric:

TREE-MAXIMUM.x/

1 while x:right ¤ NIL2 x D x:right3 return x

Both of these procedures run in O.h/ time on a tree of height h since, as in TREE-SEARCH, the sequence of nodes encountered forms a simple path downward fromthe root.

Successor and predecessorGiven a node in a binary search tree, sometimes we need to find its successor inthe sorted order determined by an inorder tree walk. If all keys are distinct, the

290 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 path15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by followingleft 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 theright subtree of 15. The node with key 13 has no right subtree, and thus its successor is its lowestancestor whose left child is also an ancestor. In this case, the node with key 15 is its successor.

TREE-SEARCH.x; k/

1 if x == NIL or k == x:key2 return x3 if k < x:key4 return TREE-SEARCH.x: left; k/5 else return TREE-SEARCH.x:right; k/

The procedure begins its search at the root and traces a simple path downward inthe tree, as shown in Figure 12.2. For each node x it encounters, it compares thekey k with x:key. If the two keys are equal, the search terminates. If k is smallerthan x:key, the search continues in the left subtree of x, since the binary-search-tree property implies that k could not be stored in the right subtree. Symmetrically,if k is larger than x:key, the search continues in the right subtree. The nodesencountered during the recursion form a simple path downward from the root ofthe tree, and thus the running time of TREE-SEARCH is O.h/, where h is the heightof the tree.

We can rewrite this procedure in an iterative fashion by “unrolling” the recursioninto a while loop. On most computers, the iterative version is more efficient.

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 smallest key greater than x:key. Thestructure of a binary search tree allows us to determine the successor of a nodewithout ever comparing keys. The following procedure returns the successor of anode x in a binary search tree if it exists, and NIL if x has the largest key in thetree:

TREE-SUCCESSOR.x/

1 if x:right ¤ NIL2 return TREE-MINIMUM.x:right/3 y D x:p4 while y ¤ NIL and x == y:right5 x D y6 y D y:p7 return y

We break the code for TREE-SUCCESSOR into two cases. If the right subtreeof node x is nonempty, then the successor of x is just the leftmost node in x’sright subtree, which we find in line 2 by calling TREE-MINIMUM.x:right/. Forexample, the successor of the node with key 15 in Figure 12.2 is the node withkey 17.

On the other hand, as Exercise 12.2-6 asks you to show, if the right subtree ofnode x is empty and x has a successor y, then y is the lowest ancestor of x whoseleft child is also an ancestor of x. In Figure 12.2, the successor of the node withkey 13 is the node with key 15. To find y, we simply go up the tree from x until weencounter a node that is the left child of its parent; lines 3–7 of TREE-SUCCESSORhandle this case.

The running time of TREE-SUCCESSOR on a tree of height h is O.h/, since weeither follow a simple path up the tree or follow a simple path down the tree. Theprocedure TREE-PREDECESSOR, which is symmetric to TREE-SUCCESSOR, alsoruns in time O.h/.

Even if keys are not distinct, we define the successor and predecessor of anynode x as the node returned by calls made to TREE-SUCCESSOR.x/ and TREE-PREDECESSOR.x/, respectively.

In summary, we have proved the following theorem.

Theorem 12.2We can implement the dynamic-set operations SEARCH, MINIMUM, MAXIMUM,SUCCESSOR, and PREDECESSOR so that each one runs in O.h/ time on a binarysearch tree of height h.

290 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 path15 ! 6 ! 7 ! 13 from the root. The minimum key in the tree is 2, which is found by followingleft 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 theright subtree of 15. The node with key 13 has no right subtree, and thus its successor is its lowestancestor whose left child is also an ancestor. In this case, the node with key 15 is its successor.

TREE-SEARCH.x; k/

1 if x == NIL or k == x:key2 return x3 if k < x:key4 return TREE-SEARCH.x: left; k/5 else return TREE-SEARCH.x:right; k/

The procedure begins its search at the root and traces a simple path downward inthe tree, as shown in Figure 12.2. For each node x it encounters, it compares thekey k with x:key. If the two keys are equal, the search terminates. If k is smallerthan x:key, the search continues in the left subtree of x, since the binary-search-tree property implies that k could not be stored in the right subtree. Symmetrically,if k is larger than x:key, the search continues in the right subtree. The nodesencountered during the recursion form a simple path downward from the root ofthe tree, and thus the running time of TREE-SEARCH is O.h/, where h is the heightof the tree.

We can rewrite this procedure in an iterative fashion by “unrolling” the recursioninto a while loop. On most computers, the iterative version is more efficient.

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 295

2 9

5

13 17

15 19

18

12

Figure 12.3 Inserting an item with key 13 into a binary search tree. Lightly shaded nodes indicatethe simple path from the root down to the position where the item is inserted. The dashed lineindicates the link in the tree that is added to insert the item.

Figure 12.3 shows how TREE-INSERT works. Just like the procedures TREE-SEARCH and ITERATIVE-TREE-SEARCH, TREE-INSERT begins at the root of thetree and the pointer x traces a simple path downward looking for a NIL to replacewith the input item ´. The procedure maintains the trailing pointer y as the parentof x. After initialization, the while loop in lines 3–7 causes these two pointersto move down the tree, going left or right depending on the comparison of ´:keywith x:key, until x becomes NIL. This NIL occupies the position where we wish toplace the input item ´. We need the trailing pointer y, because by the time we findthe NIL where ´ belongs, the search has proceeded one step beyond the node thatneeds to be changed. Lines 8–13 set the pointers that cause ´ to be inserted.

Like the other primitive operations on search trees, the procedure TREE-INSERTruns in O.h/ time on a tree of height h.

DeletionThe overall strategy for deleting a node ´ from a binary search tree T has threebasic cases but, as we shall see, one of the cases is a bit tricky.! If ´ has no children, then we simply remove it by modifying its parent to re-

place ´ with NIL as its child.! If ´ has just one child, then we elevate that child to take ´’s position in the tree

by modifying ´’s parent to replace ´ by ´’s child.! If ´ has two children, then we find ´’s successor y—which must be in ´’s right

subtree—and have y take ´’s position in the tree. The rest of ´’s original rightsubtree becomes y’s new right subtree, and ´’s left subtree becomes y’s newleft subtree. This case is the tricky one because, as we shall see, it matterswhether y is ´’s right child.

Inserción

12.3 Insertion and deletion 295

2 9

5

13 17

15 19

18

12

Figure 12.3 Inserting an item with key 13 into a binary search tree. Lightly shaded nodes indicatethe simple path from the root down to the position where the item is inserted. The dashed lineindicates the link in the tree that is added to insert the item.

Figure 12.3 shows how TREE-INSERT works. Just like the procedures TREE-SEARCH and ITERATIVE-TREE-SEARCH, TREE-INSERT begins at the root of thetree and the pointer x traces a simple path downward looking for a NIL to replacewith the input item ´. The procedure maintains the trailing pointer y as the parentof x. After initialization, the while loop in lines 3–7 causes these two pointersto move down the tree, going left or right depending on the comparison of ´:keywith x:key, until x becomes NIL. This NIL occupies the position where we wish toplace the input item ´. We need the trailing pointer y, because by the time we findthe NIL where ´ belongs, the search has proceeded one step beyond the node thatneeds to be changed. Lines 8–13 set the pointers that cause ´ to be inserted.

Like the other primitive operations on search trees, the procedure TREE-INSERTruns in O.h/ time on a tree of height h.

DeletionThe overall strategy for deleting a node ´ from a binary search tree T has threebasic cases but, as we shall see, one of the cases is a bit tricky.! If ´ has no children, then we simply remove it by modifying its parent to re-

place ´ with NIL as its child.! If ´ has just one child, then we elevate that child to take ´’s position in the tree

by modifying ´’s parent to replace ´ by ´’s child.! If ´ has two children, then we find ´’s successor y—which must be in ´’s right

subtree—and have y take ´’s position in the tree. The rest of ´’s original rightsubtree becomes y’s new right subtree, and ´’s left subtree becomes y’s newleft subtree. This case is the tricky one because, as we shall see, it matterswhether y is ´’s right child.

294 Chapter 12 Binary Search Trees

12.2-8Prove that no matter what node we start at in a height-h binary search tree, ksuccessive calls to TREE-SUCCESSOR take O.k C h/ time.12.2-9Let T be a binary search tree whose keys are distinct, let x be a leaf node, and let ybe its parent. Show that y:key is either the smallest key in T larger than x:key orthe largest key in T smaller than x:key.

12.3 Insertion and deletion

The operations of insertion and deletion cause the dynamic set represented by abinary search tree to change. The data structure must be modified to reflect thischange, but in such a way that the binary-search-tree property continues to hold.As we shall see, modifying the tree to insert a new element is relatively straight-forward, but handling deletion is somewhat more intricate.

InsertionTo 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 thatit inserts ´ into an appropriate position in the tree.

TREE-INSERT.T; ´/

1 y D NIL2 x D T:root3 while x ¤ NIL4 y D x5 if ´:key < x:key6 x D x: left7 else x D x:right8 ´:p D y9 if y == NIL

10 T:root D ´ // tree T was empty11 elseif ´:key < y:key12 y: left D ´13 else y:right D ´

A donde se Inserta 14?...

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

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.

296 Chapter 12 Binary Search Trees

The procedure for deleting a given node ´ from a binary search tree T takes asarguments pointers to T and ´. It organizes its cases a bit differently from the threecases outlined previously by considering the four cases shown in Figure 12.4.! If ´ has no left child (part (a) of the figure), then we replace ´ by its right child,

which may or may not be NIL. When ´’s right child is NIL, this case deals withthe situation in which ´ has no children. When ´’s right child is non-NIL, thiscase handles the situation in which ´ has just one child, which is its right child.

! If ´ has just one child, which is its left child (part (b) of the figure), then wereplace ´ by its left child.

! Otherwise, ´ has both a left and a right child. We find ´’s successor y, whichlies in ´’s right subtree and has no left child (see Exercise 12.2-5). We want tosplice y out of its current location and have it replace ´ in the tree.! If y is ´’s right child (part (c)), then we replace ´ by y, leaving y’s right

child alone.! Otherwise, y lies within ´’s right subtree but is not ´’s right child (part (d)).

In this case, we first replace y by its own right child, and then we replace ´by y.

In order to move subtrees around within the binary search tree, we define asubroutine TRANSPLANT, which replaces one subtree as a child of its parent withanother subtree. When TRANSPLANT replaces the subtree rooted at node u withthe subtree rooted at node !, node u’s parent becomes node !’s parent, and u’sparent ends up having ! as its appropriate child.

TRANSPLANT.T; u; !/

1 if u:p == NIL2 T:root D !3 elseif u == u:p: left4 u:p: left D !5 else u:p:right D !6 if ! ¤ NIL7 !:p D u:p

Lines 1–2 handle the case in which u is the root of T . Otherwise, u is either a leftchild or a right child of its parent. Lines 3–4 take care of updating u:p: left if uis a left child, and line 5 updates u:p:right if u is a right child. We allow ! to beNIL, and lines 6–7 update !:p if ! is non-NIL. Note that TRANSPLANT does notattempt to update !: left and !:right; doing so, or not doing so, is the responsibilityof TRANSPLANT’s caller.

12.3 Insertion and deletion 297

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

Figure 12.4 Deleting a node ´ from a binary search tree. Node ´ may be the root, a left child ofnode q, or a right child of q. (a) Node ´ has no left child. We replace ´ by its right child r , whichmay or may not be NIL. (b)Node ´ has a left child l but no right child. We replace ´ by l . (c)Node ´has two children; its left child is node l , its right child is its successor y, and y’s right child is node x.We replace ´ by y, updating y’s left child to become l , but leaving x as y’s right child. (d) Node ´has two children (left child l and right child r), and its successor y ¤ r lies within the subtree rootedat r . We replace y by its own right child x, and we set y to be r’s parent. Then, we set y to be q’schild and the parent of l .

12.3 Insertion and deletion 297

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

Figure 12.4 Deleting a node ´ from a binary search tree. Node ´ may be the root, a left child ofnode q, or a right child of q. (a) Node ´ has no left child. We replace ´ by its right child r , whichmay or may not be NIL. (b)Node ´ has a left child l but no right child. We replace ´ by l . (c)Node ´has two children; its left child is node l , its right child is its successor y, and y’s right child is node x.We replace ´ by y, updating y’s left child to become l , but leaving x as y’s right child. (d) Node ´has two children (left child l and right child r), and its successor y ¤ r lies within the subtree rootedat r . We replace y by its own right child x, and we set y to be r’s parent. Then, we set y to be q’schild and the parent of l .

298 Chapter 12 Binary Search Trees

With the TRANSPLANT procedure in hand, here is the procedure that deletesnode ´ from binary search tree T :

TREE-DELETE.T; ´/

1 if ´: left == NIL2 TRANSPLANT.T; ´; ´:right/3 elseif ´:right == NIL4 TRANSPLANT.T; ´; ´: left/5 else y D TREE-MINIMUM.´:right/6 if y:p ¤ ´7 TRANSPLANT.T; y; y:right/8 y:right D ´:right9 y:right:p D y

10 TRANSPLANT.T; ´; y/11 y: left D ´: left12 y: left:p D y

The TREE-DELETE procedure executes the four cases as follows. Lines 1–2handle the case in which node ´ has no left child, and lines 3–4 handle the case inwhich ´ has a left child but no right child. Lines 5–12 deal with the remaining twocases, in which ´ has two children. Line 5 finds node y, which is the successorof ´. Because ´ has a nonempty right subtree, its successor must be the node inthat subtree with the smallest key; hence the call to TREE-MINIMUM.´:right/. Aswe noted before, y has no left child. We want to splice y out of its current location,and it should replace ´ in the tree. If y is ´’s right child, then lines 10–12 replace ´as a child of its parent by y and replace y’s left child by ´’s left child. If y isnot ´’s left child, lines 7–9 replace y as a child of its parent by y’s right child andturn ´’s right child into y’s right child, and then lines 10–12 replace ´ as a child ofits parent by y and replace y’s left child by ´’s left child.

Each line of TREE-DELETE, including the calls to TRANSPLANT, takes constanttime, except for the call to TREE-MINIMUM in line 5. Thus, TREE-DELETE runsin O.h/ time on a tree of height h.

In summary, we have proved the following theorem.

Theorem 12.3We can implement the dynamic-set operations INSERT and DELETE so that eachone runs in O.h/ time on a binary search tree of height h.

a

b

y

Si “y” es el hijo derecho de

“z”

c

d

Ejercicio:

12.3 Insertion and deletion 295

2 9

5

13 17

15 19

18

12

Figure 12.3 Inserting an item with key 13 into a binary search tree. Lightly shaded nodes indicatethe simple path from the root down to the position where the item is inserted. The dashed lineindicates the link in the tree that is added to insert the item.

Figure 12.3 shows how TREE-INSERT works. Just like the procedures TREE-SEARCH and ITERATIVE-TREE-SEARCH, TREE-INSERT begins at the root of thetree and the pointer x traces a simple path downward looking for a NIL to replacewith the input item ´. The procedure maintains the trailing pointer y as the parentof x. After initialization, the while loop in lines 3–7 causes these two pointersto move down the tree, going left or right depending on the comparison of ´:keywith x:key, until x becomes NIL. This NIL occupies the position where we wish toplace the input item ´. We need the trailing pointer y, because by the time we findthe NIL where ´ belongs, the search has proceeded one step beyond the node thatneeds to be changed. Lines 8–13 set the pointers that cause ´ to be inserted.

Like the other primitive operations on search trees, the procedure TREE-INSERTruns in O.h/ time on a tree of height h.

DeletionThe overall strategy for deleting a node ´ from a binary search tree T has threebasic cases but, as we shall see, one of the cases is a bit tricky.! If ´ has no children, then we simply remove it by modifying its parent to re-

place ´ with NIL as its child.! If ´ has just one child, then we elevate that child to take ´’s position in the tree

by modifying ´’s parent to replace ´ by ´’s child.! If ´ has two children, then we find ´’s successor y—which must be in ´’s right

subtree—and have y take ´’s position in the tree. The rest of ´’s original rightsubtree becomes y’s new right subtree, and ´’s left subtree becomes y’s newleft subtree. This case is the tricky one because, as we shall see, it matterswhether y is ´’s right child.

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.


Recommended