Matebachillerato.files.wordpress.com



Notice something different? We've made a few improvements to Wikipedia. Learn more! Binary search tree ?rbol binario de búsqueda From Wikipedia, the free encyclopedia De Wikipedia, la enciclopedia libre Jump to: HYPERLINK "" \l "head" navigation , HYPERLINK "" \l "p-search" search Saltar a navegación , búsqueda A binary search tree of size 9 and depth 3, with root 8 and leaves 1, 4, 7 and 13 Un árbol de búsqueda binaria de tama?o 9 y la profundidad de 3, con raíz y hojas de 8 1, 4, 7 y 13 In computer science , a binary search tree ( BST ) or ordered binary tree is a node-based binary tree data structure which has the following properties: [ 1 ] En HYPERLINK "" \o "Informática" ciencias de la computación , un árbol binario de búsqueda (BST) o solicitarse en árbol binario es un nodo basado en árbol binario estructura de datos que tiene las siguientes propiedades: [1] The left subtree of a node contains only nodes with keys less than the node's key. La izquierda subárbol de un nodo contiene sólo los nodos con claves de menos de nodo tecla. The right subtree of a node contains only nodes with keys greater than or equal to the node's key. El subárbol derecho de un nodo contiene sólo los nodos con claves de mayor o igual a la clave del nodo. Both the left and right subtrees must also be binary search trees. Tanto el subárboles izquierdo y derecho también debe ser árboles binarios de búsqueda. From the above properties it naturally follows that: De las propiedades anteriores la consecuencia natural es que: Each node (item in the tree) has a distinct key. Cada nodo (elemento del árbol) tiene una clave distinta. Generally, the information represented by each node is a record rather than a single data element. En general, la información representada por cada nodo es un registro en lugar de un único elemento de datos. However, for sequencing purposes, nodes are compared according to their keys rather than any part of their associated records. Sin embargo, para la secuenciación de los propósitos, los nodos son comparados de acuerdo a sus teclas en lugar de cualquier parte de sus registros asociados. The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient. La principal ventaja de los árboles de búsqueda binaria sobre otras estructuras de datos es que los relacionados con algoritmos de clasificación y algoritmos de búsqueda como el recorrido en orden puede ser muy eficiente. Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets , multisets , and associative arrays . árboles binarios de búsqueda son fundamentales una estructura de datos utilizada para construir estructuras de datos más abstractos, tales como conjuntos , conjuntos múltiples , y arrays asociativos . Contents Contenido [ HYPERLINK "javascript:toggleToc()" hide]1 Operations 1 Operaciones 1.1 Searching 1,1 búsqueda 1.2 Insertion 1.2 Inserción 1.3 Deletion 1.3 Supresión 1.4 Traversal 1.4 Traversal 1.5 Sort Ordenar 1,5 2 Types 2 Tipos 2.1 Performance comparisons 2.1 Comportamiento comparaciones 2.2 Optimal binary search trees 2,2 árboles de búsqueda binaria óptima 3 See also 3 Véase también 4 References 4 Referencias 5 Further reading 5 Véase también 6 External links 6 Enlaces externos [ edit ] Operations [ HYPERLINK "" \o "sección Editar: Operaciones" editar ] Operaciones Operations on a binary tree require comparisons between nodes. Las operaciones en un árbol binario requieren comparaciones entre los nodos. These comparisons are made with calls to a comparator , which is a subroutine that computes the total order (linear order) on any two values. Estas comparaciones se hacen con llamadas a un comparador , que es una subrutina que calcula el total del pedido (orden lineal) en cualquiera de los dos valores. This comparator can be explicitly or implicitly defined, depending on the language in which the BST is implemented. Esta comparación puede ser explícita o implícitamente definido, según el idioma en que se aplica el BST. [ edit ] Searching [ editar ] Búsqueda Searching a binary tree for a specific value can be a recursive or iterative process. Buscando un árbol binario de un valor específico puede ser un recursivo o iterativo proceso. This explanation covers a recursive method. Esta explicación abarca un método iterativo. We begin by examining the root node . Comenzamos examinando el nodo raíz . If the tree is null, the value we are searching for does not exist in the tree. Si el árbol es nulo, el valor que está buscando no existe en el árbol. Otherwise, if the value equals the root, the search is successful. De lo contrario, si el valor es igual a la raíz, la búsqueda tiene éxito. If the value is less than the root, search the left subtree. Si el valor es inferior a la raíz, busque en el subárbol izquierdo. Similarly, if it is greater than the root, search the right subtree. Del mismo modo, si ésta es superior a la raíz, busque en el subárbol derecho. This process is repeated until the value is found or the indicated subtree is null. Este proceso se repite hasta que el valor se encuentra o el subárbol indicado es nulo. If the searched value is not found before a null subtree is reached, then the item must not be present in the tree. Si el valor buscado no se encuentra ante un subárbol nula es alcanzado, entonces el tema no debe estar presente en el árbol. Here is the search algorithm in the Python programming language : Aquí está el algoritmo de búsqueda en el lenguaje de programación Python : # 'node' refers to the parent-node in this case # 'Nodo' se refiere a la relación padre-nodo en este caso def search_binary_tree ( node, key ) : def search_binary_tree (nodo, clave): if node is None : si el nodo es None: return None # key not found Ninguno de retorno que no se encuentra la tecla # if key < node. key : si el nodo <clave. clave: return search_binary_tree ( node. leftChild , key ) search_binary_tree retorno (node. leftChild, clave) elif key > node. key : elif nodo> clave. clave: return search_binary_tree ( node. rightChild , key ) search_binary_tree retorno (node. rightChild, clave) else : # key is equal to node key else: # clave es igual al nodo clave return node. value # found key nodo de retorno. valor # encontrados clave… or equivalent HYPERLINK "(programming_language)&rurl=translate..gt&usg=ALkJrhjtBIXCmalU0hpuNWjYhp41E5g2Ag" \o "Haskell (lenguaje de programación)" Haskell : ... O equivalente Haskell : searchBinaryTree _ NullNode = Nothing searchBinaryTree NullNode _ = Nothing searchBinaryTree key ( Node nodeKey nodeValue ( leftChild , rightChild ) ) = searchBinaryTree clave (nodeKey nodeValue Nodo (leftChild, rightChild)) = case compare key nodeKey of caso comparar nodeKey clave de LT -> searchBinaryTree key leftChild LT - searchBinaryTree> Tecla leftChild GT -> searchBinaryTree key rightChild GT - searchBinaryTree> Tecla rightChild EQ -> Just nodeValue EQ -> Solamente nodeValueThis operation requires O (log n ) time in the average case, but needs O ( n ) time in the worst-case, when the unbalanced tree resembles a linked list ( degenerate tree ). Esta operación requiere O (log n) en el caso promedio, pero necesita O (n) el tiempo en el peor de los casos, cuando el árbol se parece a un desequilibrio lista enlazada ( árbol degenerado ). Assuming that BinarySearchTree is a class with a member function "search(int)" and a pointer to the root node, the algorithm is also easily implemented in terms of an iterative approach. Suponiendo que BinarySearchTree es una clase con una función miembro "de búsqueda (int)" y un puntero al nodo raíz, el algoritmo también es fácil de implementar en términos de un enfoque iterativo. The algorithm enters a loop, and decides whether to branch left or right depending on the value of the node at each parent node. El algoritmo entra en un bucle, y decide si la rama izquierda o derecha según el valor del nodo en cada nodo primario. bool BinarySearchTree :: search ( int val ) bool BinarySearchTree:: buscar (int val){ ( Node * next = this - > root ( ) ; Nodo * siguiente = esto - root> (); while ( next ! = 0 ) while (siguiente! = 0) { ( if ( val == next - > value ( ) ) if (val == siguiente - valor> ()) { ( return true ; return true; } ) else if ( val < next - > value ( ) ) else if (val <Los - valor> ()) { ( next = next - > left ( ) ; next = siguiente - a la izquierda> (); } ) else if ( val > next - > value ( ) ) else if (val siguiente> - valor> ()) { ( next = next - > right ( ) ; next = siguiente -> derecha (); } ) } ) //not found / / No encontrado return false ; return false;} )Here is the search algorithm in the Java programming language : Aquí está el algoritmo de búsqueda en el lenguaje de programación Java : public boolean search ( TreeNode node, int data ) { búsqueda booleana pública (nodo TreeNode, los datos int) (if ( node == null ) { if (nodo == null) (return false ; return false;} )if ( node. getData ( ) == data ) { if (node. getData () == data) (return true ; return true;} else if ( data < node. getData ( ) ) { ) Else if (datos <nodo. GetData ()) (// data must be in left subtree / / Datos deben estar en subárbol izquierdoreturn search ( node. getLeft ( ) , data ) ; búsqueda de retorno (node. getLeft (), datos);} else { Else ()// data must be in right subtree / / Datos deben estar en subárbol derechoreturn search ( node. getRight ( ) , data ) ; búsqueda de retorno (node. GetRight (), datos);} )} )[ edit ] Insertion [ editar ] Inserción Insertion begins as a search would begin; if the root is not equal to the value, we search the left or right subtrees as before. La inserción comienza como una búsqueda comenzaría, si la raíz no es igual al valor, buscamos la izquierda o derecha subárboles como antes. Eventually, we will reach an external node and add the value as its right or left child, depending on the node's value. Con el tiempo, llegaremos a un nodo externo y agregue el valor como su hijo derecho o izquierdo, dependiendo del valor del nodo. In other words, we examine the root and recursively insert the new node to the left subtree if the new value is less than the root, or the right subtree if the new value is greater than or equal to the root. En otras palabras, se examinan la raíz y de forma recursiva insertar el nuevo nodo al subárbol izquierdo si el nuevo valor es inferior a la raíz, o el subárbol de la derecha si el nuevo valor es mayor o igual a la raíz. Here's how a typical binary search tree insertion might be performed in C++ : Así es como una típica búsqueda de la inserción árbol binario puede ser realizado en C + + : /* Inserts the node pointed to by "newNode" into the subtree rooted at "treeNode" */ / * Inserta el nodo apuntado por "nodo_nuevo" en el subárbol con raíz en "TreeNode" * / void InsertNode ( Node * & treeNode, Node * newNode ) insertarNodo vacío (* Nodo y TreeNode Nodo * nodo_nuevo) { ( if ( treeNode == NULL ) if (TreeNode == NULL) treeNode = newNode ; TreeNode = nodo_nuevo; else if ( newNode - > key < treeNode - > key ) else if (nodo_nuevo - clave TreeNode <> -> Clave) InsertNode ( treeNode - > left, newNode ) ; InsertarNodo (TreeNode - izquierda>, nodo_nuevo); else más InsertNode ( treeNode - > right, newNode ) ; InsertarNodo (TreeNode -> derecha, nodo_nuevo); } )The above "destructive" procedural variant modifies the tree in place. Lo anterior "destructiva" variante de procedimiento modifica el árbol en su lugar. It uses only constant space, but the previous version of the tree is lost. Utiliza solamente el espacio constante, pero la versión anterior del árbol se pierde. Alternatively, as in the following Python example, we can reconstruct all ancestors of the inserted node; any reference to the original tree root remains valid, making the tree a persistent data structure : Por otra parte, como en el siguiente Python ejemplo, podemos reconstruir todos los ancestros del nodo insertado, cualquier referencia a la raíz del árbol original sigue siendo válida, haciendo que el árbol de una estructura de datos persistente : def binary_tree_insert ( node, key, value ) : def binary_tree_insert (nodo, clave, valor): if node is None : si el nodo es None: return TreeNode ( None , key, value, None ) volver TreeNode (Ninguno, clave, valor, ninguno) if key == node. key : si la clave == nodo. clave: return TreeNode ( node. left , key, value, node. right ) TreeNode retorno (node. izquierda, la tecla, el valor, el nodo. Derecha) if key < node. key : si el nodo <clave. clave: return TreeNode ( binary_tree_insert ( node. left , key, value ) , node. key , node. value , node. right ) volver TreeNode (binary_tree_insert (node. izquierda, clave, valor), el nodo. clave, nodo. valor, nodo. derecha) else : otra cosa: return TreeNode ( node. left , node. key , node. value , binary_tree_insert ( node. right , key, value ) ) TreeNode retorno (node. izquierda, nodo. Clave, nodo. Valor, binary_tree_insert (node. derecho, clave, valor))The part that is rebuilt uses Θ(log n ) space in the average case and Ω( n ) in the worst case (see big-O notation ). La parte que se vuelve a generar usos Θ (log n) de espacio en el caso promedio y Ω (n) en el peor de los casos (véase la notación-O ). In either version, this operation requires time proportional to the height of the tree in the worst case, which is O (log n ) time in the average case over all trees, but Ω( n ) time in the worst case. En cualquier versión, esta operación requiere un tiempo proporcional a la altura del árbol en el peor de los casos, que es O (log n) en el caso promedio de todos los árboles, pero (n Ω) tiempo en el peor de los casos. Another way to explain insertion is that in order to insert a new node in the tree, its value is first compared with the value of the root. Otra manera de explicar la inserción es que para insertar un nuevo nodo en el árbol, su valor se compara primero con el valor de la raíz. If its value is less than the root's, it is then compared with the value of the root's left child. Si su valor es inferior a la raíz, que se compara con el valor del hijo izquierdo de la raíz. If its value is greater, it is compared with the root's right child. Si su valor es mayor, se la compara con el hijo derecho de la raíz. This process continues, until the new node is compared with a leaf node, and then it is added as this node's right or left child, depending on its value. Este proceso continúa hasta que el nuevo nodo se compara con un nodo hoja, y luego se a?ade como derecho de este nodo o un ni?o a la izquierda, dependiendo de su valor. There are other ways of inserting nodes into a binary tree, but this is the only way of inserting nodes at the leaves and at the same time preserving the BST structure. Hay otras maneras de insertar nodos en un árbol binario, pero esta es la única manera de insertar nodos en las hojas y, al mismo tiempo preservar la estructura de BST. Here is an iterative approach to inserting into a binary search tree the in Java Programming Language : Aquí hay un enfoque iterativo para la inserción en un árbol de búsqueda binaria en el Lenguaje de Programación Java : public void insert ( int data ) { public void insertar (datos int) (if ( root == null ) { if (raiz == null) (root = new TreeNode ( data, null , null ) ; root = TreeNode nueva (datos, null, null);} else { Else ()TreeNode current = root ; TreeNode actual root =;while ( current != null ) { while (actual! = null) (if ( data < current. getData ( ) ) { if (datos <actual. getData ()) (// insert left / / Inserto la izquierdaif ( current. getLeft ( ) == null ) { if (current. getLeft () == null) (current. setLeft ( new TreeNode ( data, null , null ) ) ; actual. setLeft (nuevo TreeNode (datos, null, null));return ; de retorno;} else { Else ()current = current. getLeft ( ) ; actual = actual. getLeft ();} ) } else { Else ()// insert right / / Inserto la derechaif ( current. getRight ( ) == null ) { if (current. GetRight () == null) (current. setRight ( new TreeNode ( data, null , null ) ) ; actual. setRight (nuevo TreeNode (datos, null, null));return ; de retorno;} else { Else ()current = current. getRight ( ) ; actual = actual. GetRight ();} )} )} )} )} )Below is a recursive approach to the insertion method. A continuación se muestra un enfoque recursivo al método de inserción. As pointers are not available in Java we must return a new node pointer to the caller as indicated by the final line in the method. Como los punteros no están disponibles en Java tenemos que devolver un puntero nuevo nodo a la persona que llama como se indica por la línea final en el método. public TreeNode insert ( TreeNode node, int data ) { pública insertar TreeNode (nodo TreeNode, los datos int) (if ( node == null ) { if (nodo == null) (node = new TreeNode ( data, null , null ) ; = nodo TreeNode nueva (datos, null, null);} else { Else ()if ( data < node. getData ( ) ) { if (datos <nodo. getData ()) (// insert left / / Inserto la izquierdanode. left = insert ( node. getLeft ( ) , data ) ; nodo. izquierda = inserción (node. getLeft (), datos);} else { Else ()// insert right / / Inserto la derechanode. right = insert ( node. getRight ( ) , data ) ; nodo. derecha = inserción (node. GetRight (), datos);} )} )return node ; volver nodo;} )[ edit ] Deletion [ editar ] Supresión There are three possible cases to consider: Hay tres posibles casos a considerar: Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply remove it from the tree. Eliminación de una hoja (nodo sin hijos): Cómo eliminar una hoja es fácil, ya que simplemente puede eliminarlo del árbol. Deleting a node with one child: Delete it and replace it with its child. Eliminar un nodo con un hijo: Eliminarlo y sustituirlo por su hijo. Deleting a node with two children: Call the node to be deleted "N". Eliminar un nodo con dos hijos: Llame al nodo que se borró "N". Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, "R". No elimine N. En su lugar, elegir entre su nodo en el sucesor de orden o su nodo antecesor en orden, "R". Replace the value of N with the value of R, then delete R. (Note: R itself has up to one child.) Vuelva a colocar el valor de N con el valor de R, a continuación, elimine R. (Nota: R se tiene hasta un ni?o.) As with all binary trees, a node's in-order successor is the left-most child of its right subtree, and a node's in-order predecessor is the right-most child of its left subtree. Al igual que con todos los árboles binarios, en orden sucesor un nodo es el hijo más a la izquierda de su subárbol derecho, y en orden un predecesor del nodo es el hijo más a la derecha de su subárbol izquierdo. In either case, this node will have zero or one children. En cualquier caso, este nodo tiene cero o un ni?o. Delete it according to one of the two simpler cases above. Eliminar de acuerdo con uno de los dos casos más sencillos anteriores. Consistently using the in-order successor or the in-order predecessor for every instance of the two-child case can lead to an unbalanced tree, so good implementations add inconsistency to this selection. El uso constante de la orden o el sucesor en orden antecesor en cada instancia del caso de dos ni?os-puede conducir a un desequilibrio de árboles, por lo que a?adimos una buena implementaciones inconsistencia de esta selección. Running Time Analysis: Although this operation does not always traverse the tree down to a leaf, this is always a possibility; thus in the worst case it requires time proportional to the height of the tree. Tiempo de análisis: Aunque esta operación no siempre recorrer el árbol hasta una hoja, esto es siempre una posibilidad, por lo que en el peor de los casos se requiere un tiempo proporcional a la altura del árbol. It does not require more even when the node has two children, since it still follows a single path and does not visit any node twice. No requiere más aún cuando el nodo tiene dos hijos, dado que todavía sigue un camino único y no visita ningún nodo dos veces. Here is the code in Python: Este es el código en Python: def findMin ( self ) : def findMin (self): '' ' ''' Finds the smallest element that is a child of *self* Busca el elemento más peque?o que es un hijo de la libre * * ' '' ''' current_node = self current_node = auto while current_node. left_child : mientras current_node. left_child: current_node = current_node. left_child current_node = current_node. left_child return current_node volver current_node def replace_node_in_parent ( self , new_value= None ) : def replace_node_in_parent (self, = Ninguno new_value): '' ' ''' Removes the reference to *self* from *self.parent* and replaces it with *new_value*. Elimina la referencia a * * * * yo de self.parent y lo reemplaza con * new_value *. ' '' ''' if self == self . parent . left_child : si trabaja por cuenta propia ==. padres. left_child: self . parent . left_child = new_value uno mismo. padres. left_child = new_value else : otra cosa: self . parent . right_child = new_value uno mismo. padres. right_child = new_value if new_value: si new_value: new_value. parent = self . parent new_value. padres = yo. padres def binary_tree_delete ( self , key ) : def binary_tree_delete (self, clave): if key < self . key : si <clave auto. clave: self . left_child . binary_tree_delete ( key ) uno mismo. left_child. binary_tree_delete (clave) elif key > self . key : elif clave auto>. clave: self . right_child . binary_tree_delete ( key ) uno mismo. right_child. binary_tree_delete (clave) else : # delete the key here else: # eliminar la clave aquí if self . left_child and self . right_child : # if both children are present si uno mismo. left_child y yo. right_child: # si ambos la presencia de ni?os # get the smallest node that's bigger than *self* # Obtiene el más peque?o nodo que es más grande que uno mismo * * successor = self . right_child . findMin ( ) sucesor = yo. right_child. findMin () self . key = successor. key key = sucesor. auto. clave # if *successor* has a child, replace it with that # * * Si el sucesor tiene un hijo, que se sustituya por # at this point, it can only have a *right_child* # En este momento, sólo puede tener un right_child * * # if it has no children, *right_child* will be "None" # Si no tiene hijos, * * right_child será "Ninguno" successor. replace_node_in_parent ( successor. right_child ) sucesor. replace_node_in_parent (successor. right_child) elif self . left_child or self . right_child : # if the node has only one child elif auto. left_child o por cuenta propia. right_child: # si el nodo tiene un solo hijo if self . left_child : si uno mismo. left_child: self . replace_node_in_parent ( self . left_child ) uno mismo. replace_node_in_parent (auto. left_child) else : otra cosa: self . replace_node_in_parent ( self . right_child ) uno mismo. replace_node_in_parent (auto. right_child) else : # this node has no children else: # este nodo no tiene hijos self . replace_node_in_parent ( None ) uno mismo. replace_node_in_parent (Ninguno)[ edit ] Traversal [ editar ] Recorrido Main article: Tree traversal Artículo principal: recorrido de árbol Once the binary search tree has been created, its elements can be retrieved in-order by recursively traversing the left subtree of the root node, accessing the node itself, then recursively traversing the right subtree of the node, continuing this pattern with each node in the tree as it's recursively accessed. Una vez que el árbol de búsqueda binaria se ha creado, sus elementos pueden ser recuperados en orden de forma recursiva que atraviesa el subárbol izquierdo del nodo raíz, el acceso a la misma nodo, a continuación, recorrer recursivamente el subárbol derecho del nodo, continuando este patrón con cada nodo El árbol ya que es visitada de forma recursiva. As with all binary trees, one may conduct a pre-order traversal or a post-order traversal , but neither are likely to be useful for binary search trees. Al igual que con todos los árboles binarios, se puede realizar un recorrido pre-orden o una orden de recorrido de post , pero tampoco son susceptibles de ser utilizadas para los árboles binarios de búsqueda. The code for in-order traversal in Python is given below. El código en el orden de recorrido en Python es la siguiente. It will call callback for every node in the tree. Se ha previsto de devolución de llamada para cada nodo en el árbol. def traverse_binary_tree ( node, callback ) : def traverse_binary_tree (nodo, de devolución de llamada): if node is None : si el nodo es None: return volver traverse_binary_tree ( node. leftChild , callback ) traverse_binary_tree (node. leftChild, devolución de llamada) callback ( node. value ) de devolución de llamada (node. valor) traverse_binary_tree ( node. rightChild , callback ) traverse_binary_tree (node. rightChild, devolución de llamada)Traversal requires Ω( n ) time, since it must visit every node. Traversal requiere HYPERLINK "" \l "Related_asymptotic_notations" \o "Big O notación" Ω (n) el tiempo, ya que debe visitar cada nodo. This algorithm is also O( n ), so it is asymptotically optimal . Este algoritmo es O (n), por lo que es asintóticamente óptima . [ edit ] Sort [ HYPERLINK "" \o "sección Editar: Ordenar" editar ] Ordenar A binary search tree can be used to implement a simple but efficient sorting algorithm . Un árbol de búsqueda binaria se puede utilizar para poner en práctica un sencillo pero eficiente algoritmo de ordenación . Similar to heapsort , we insert all the values we wish to sort into a new ordered data structure—in this case a binary search tree—and then traverse it in order, building our result: Al igual que heapsort , insertamos todos los valores que desea ordenar en nuevos ordenó la estructura de datos, en este caso un árbol de búsqueda binaria, y luego recorrer en ella el orden, la construcción de nuestro resultado: def build_binary_tree ( values ) : def build_binary_tree (valores): tree = None árbol = Ninguno for v in values: para v en valores: tree = binary_tree_insert ( tree, v ) = árbol binary_tree_insert (árbol, v) return tree retorno de árboles def get_inorder_traversal ( root ) : get_inorder_traversal def (root): '' ' ''' Returns a list containing all the values in the tree, starting at *root*. Devuelve una lista que contiene todos los valores en el árbol, comenzando en la raíz * *. Traverses the tree in-order(leftChild, root, rightChild). Recorre el árbol en orden (leftChild, raíz, rightChild). ' '' ''' result = [ ] resultado = [] traverse_binary_tree ( root, lambda element: result. append ( element ) ) traverse_binary_tree (raíz, elemento lambda: resultado. append (elemento)) return result return resultadoThe worst-case time of build_binary_tree is Θ( n 2 ) —if you feed it a sorted list of values, it chains them into a linked list with no left subtrees. El caso peor tiempo de build_binary_tree es Θ (n 2)-Si le das una lista ordenada de valores, se los encadena en una lista enlazada sin subárboles izquierdo. For example, traverse_binary_tree([1, 2, 3, 4, 5]) yields the tree (1 (2 (3 (4 (5))))) . Por ejemplo, traverse_binary_tree([1, 2, 3, 4, 5]) se obtiene el árbol (1 (2 (3 (4 (5))))) . There are several schemes for overcoming this flaw with simple binary trees; the most common is the self-balancing binary search tree . Hay varios planes para superar esta falencia con simples árboles binarios, el más común es el de equilibrio de árbol binario de búsqueda auto . If this same procedure is done using such a tree, the overall worst-case time is O ( n log n ), which is asymptotically optimal for a comparison sort . Si este mismo procedimiento se realiza mediante un árbol, el peor de los casos el tiempo total es O (n log n), que es asintóticamente óptima para un tipo de comparación . In practice, the poor cache performance and added overhead in time and space for a tree-based sort (particularly for node allocation ) make it inferior to other asymptotically optimal sorts such as heapsort for static list sorting. En la práctica, los pobres caché de rendimiento y agregó sobrecarga en el tiempo y espacio para una base tipo de árboles (en particular para el nodo de asignación ) que sea asintóticamente óptima a otros tipos inferiores, tales como heapsort para ordenar la lista estática. On the other hand, it is one of the most efficient methods of incremental sorting , adding items to a list over time while keeping the list sorted at all times. Por otra parte, es uno de los métodos más eficientes de selección adicionales, agregar elementos a una lista con el tiempo, manteniendo la lista ordenada en todo momento. [ edit ] Types [ editar ] Tipos There are many types of binary search trees. AVL trees and red-black trees are both forms of self-balancing binary search trees . Hay muchos tipos de árboles binarios de búsqueda. HYPERLINK "" \o "AVL árbol" AVL árboles y los árboles rojo-negro son las formas de auto-equilibrio de los árboles binarios de búsqueda . A splay tree is a binary search tree that automatically moves frequently accessed elements nearer to the root. Un árbol de angulación es un árbol de búsqueda binaria que se mueve automáticamente visitada con frecuencia los elementos más cerca de la raíz. In a treap ("tree heap "), each node also holds a priority and the parent node has higher priority than its children. En un treap ("árbol montón "), cada nodo también tiene una prioridad y el nodo primario tiene mayor prioridad que a sus hijos. Two other titles describing binary search trees are that of a complete and degenerate tree. Otros dos títulos que describen los árboles de búsqueda binaria es que de un árbol completo y degenerada. A complete tree is a tree with n levels, where for each level d <= n - 1, the number of existing nodes at level d is equal to 2 d . Un árbol completo es un árbol con n niveles, donde para cada nivel d <= n - 1, el número de nodos existentes a nivel d es igual a 2 d. This means all possible nodes exist at these levels. Esto significa que todos los nodos posibles existen en estos niveles. An additional requirement for a complete binary tree is that for the n th level, while every node does not have to exist, the nodes that do exist must fill from left to right. Un requisito adicional para que un árbol binario completo es que para n ? nivel, mientras que cada nodo no tiene que existir, los nodos que existan deben llenar de izquierda a derecha. A degenerate tree is a tree where for each parent node, there is only one associated child node. Un árbol degenerado es un árbol donde cada nodo primario, sólo hay un nodo secundario asociado. What this means is that in a performance measurement, the tree will essentially behave like a linked list data structure. Lo que esto significa es que en una medición del rendimiento, el árbol esencialmente se comportará como una lista enlazada estructura de datos. [ HYPERLINK "" \o "sección Editar: Las comparaciones de rendimiento" edit ] Performance comparisons [ HYPERLINK "" \o "sección Editar: Las comparaciones de rendimiento" editar ] comparaciones de rendimiento DA Heger (2004) HYPERLINK "" \l "cite_note-1" [ 2 ] presented a performance comparison of binary search trees. HYPERLINK "" \o "Treap" Treap was found to have the best average performance, while HYPERLINK "" \o "árbol rojo-negro" red-black tree was found to have the smallest amount of performance fluctuations. DA Heger (2004) HYPERLINK "" \l "cite_note-1" [2] presenta una comparación de rendimiento de los árboles binarios de búsqueda. HYPERLINK "" \o "Treap" Treap se encontró que la media de mejor rendimiento, mientras que HYPERLINK "" \o "árbol rojo-negro" -negro árbol rojo se encontró que la cantidad más peque?a de las fluctuaciones de rendimiento. [ HYPERLINK "" \o "Editar sección: los árboles binarios de búsqueda óptima" edit ] Optimal binary search trees [ HYPERLINK "" \o "Editar sección: los árboles binarios de búsqueda óptima" editar ] árboles binarios de búsqueda óptima If we don't plan on modifying a search tree, and we know exactly how often each item will be accessed, we can construct an optimal binary search tree , which is a search tree where the average cost of looking up an item (the expected search cost ) is minimized. Si no va a modificar un árbol de búsqueda, y sabemos exactamente con qué frecuencia cada artículo será accesible, podemos construir un árbol binario de búsqueda óptimo, que es un árbol de búsqueda donde el coste medio de buscar un artículo (el esperado coste de búsqueda) se reduce al mínimo. Even if we only have estimates of the search costs, such a system can considerably speed up lookups on average. Incluso si sólo tenemos estimaciones de los costos de búsqueda, este sistema puede acelerar considerablemente las búsquedas en promedio. For example, if you have a BST of English words used in a HYPERLINK "" \o "Corrector ortográfico" spell checker , you might balance the tree based on word frequency in HYPERLINK "" \o "Texto corpus" text corpora , placing words like "the" near the root and words like "agerasia" near the leaves. Por ejemplo, si usted tiene una BST de las palabras utilizadas en Inglés un HYPERLINK "" \o "Corrector ortográfico" corrector ortográfico , que podría equilibrar el árbol basado en la frecuencia de palabras en el HYPERLINK "" \o "Texto corpus" corpus de texto , colocando palabras como "el" cerca de la raíz y palabras como "agerasia" cerca de las hojas. Such a tree might be compared with HYPERLINK "" \o "Huffman árbol" Huffman trees , which similarly seek to place frequently-used items near the root in order to produce a dense information encoding; however, Huffman trees only store data elements in leaves and these elements need not be ordered. Este árbol puede ser comparado con HYPERLINK "" \o "Huffman árbol" los árboles Huffman , que igualmente pretenden poner Artículos de uso frecuente cerca de la raíz a fin de producir una densa información de codificación, sin embargo, los árboles Huffman elementos de datos única tienda en hojas, y esos elementos no tiene que ser ordenado. If we do not know the sequence in which the elements in the tree will be accessed in advance, we can use HYPERLINK "" \o "Biselado árbol" splay trees which are asymptotically as good as any static search tree we can construct for any particular sequence of lookup operations. Si no sabemos la secuencia en que los elementos en el árbol se tendrá acceso con antelación, podemos utilizar HYPERLINK "" \o "Biselado árbol" árboles splay que son asintóticamente tan bueno como cualquier árbol de búsqueda estática podemos construir para cualquier secuencia particular de operaciones de búsqueda. Alphabetic trees are Huffman trees with the additional constraint on order, or, equivalently, search trees with the modification that all elements are stored in the leaves. alfabético árboles son árboles Huffman con la restricción adicional sobre el orden, o, equivalentemente, árboles de búsqueda con la modificación que todos los elementos se almacenan en las hojas. Faster algorithms exist for optimal alphabetic binary trees (OABTs). algoritmos más rápidos existentes para una óptima árboles binarios alfabéticos (OABTs). Example: Ejemplo: procedure Optimum Search Tree(f, f?, c): procedimiento de búsqueda del árbol óptimo (f, f, c): for j = 0 to n do para j = 0 hasta n hacer c[j, j] = 0, F[j, j] = f?j c [j, j] = 0, M j [, j] = f'j for d = 1 to n do para d = 1 hasta n hacer for i = 0 to (n ? d) do para i = 0 a (n - d) hacer j = i + d j = i + d F[i, j] = F[i, j ? 1] + f? + f?j M [i, j] = F [i, j - 1] + f '+ f'j c[i, j] = MIN(i<k<=j){c[i, k ? 1] + c[k, j]} + F[i, j] c [i, j] = MIN (i <k <= j) (c [i, k - 1] + c [k, j]) + F [i, j][ edit ] See also [ editar ] Véase también Binary search Búsqueda binaria Binary tree ?rbol binario Self-balancing binary search tree Uno mismo-equilibrio del árbol de búsqueda binaria Randomized binary search tree árbol de búsqueda binaria aleatorios B-tree B-tree Data structure ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download