Provided by: manpages-es-dev_4.13-4_all 

NOMBRE
tsearch, tfind, tdelete, twalk, tdestroy - manage a binary search tree
SINOPSIS
#include <search.h>
typedef enum { preorder, postorder, endorder, leaf } VISIT;
void *tsearch(const void *key, void **rootp,
int (*compar)(const void *, const void *));
void *tfind(const void *key, void *const *rootp,
int (*compar)(const void *, const void *));
void *tdelete(const void *key, void **rootp,
int (*compar)(const void *, const void *));
void twalk(const void *root,
void (*action)(const void *nodep, VISIT which,
int depth));
#define _GNU_SOURCE /* Vea feature_test_macros(7) */
#include <search.h>
void twalk_r(const void *root,
void (*action)(const void *nodep, VISIT which,
void *closure),
void *closure);
void tdestroy(void *root, void (*free_node)(void *nodep));
DESCRIPCIÓN
tsearch(), tfind(), twalk(), and tdelete() manage a binary search tree. They are generalized from Knuth
(6.2.2) Algorithm T. The first field in each node of the tree is a pointer to the corresponding data
item. (The calling program must store the actual data.) compar points to a comparison routine, which
takes pointers to two items. It should return an integer which is negative, zero, or positive, depending
on whether the first item is less than, equal to, or greater than the second.
tsearch() searches the tree for an item. key points to the item to be searched for. rootp points to a
variable which points to the root of the tree. If the tree is empty, then the variable that rootp points
to should be set to NULL. If the item is found in the tree, then tsearch() returns a pointer to the
corresponding tree node. (In other words, tsearch() returns a pointer to a pointer to the data item.)
If the item is not found, then tsearch() adds it, and returns a pointer to the corresponding tree node.
tfind() es como tsearch(), sólo que si no encuentra el elemento tfind() devuelve NULL.
tdelete() borra un elemento del árbol. Sus argumentos son los mismos que los de tsearch().
twalk() performs depth-first, left-to-right traversal of a binary tree. root points to the starting
node for the traversal. If that node is not the root, then only part of the tree will be visited.
twalk() calls the user function action each time a node is visited (that is, three times for an internal
node, and once for a leaf). action, in turn, takes three arguments. The first argument is a pointer to
the node being visited. The structure of the node is unspecified, but it is possible to cast the pointer
to a pointer-to-pointer-to-element in order to access the element stored within the node. The
application must not modify the structure pointed to by this argument. The second argument is an integer
which takes one of the values preorder, postorder, or endorder depending on whether this is the first,
second, or third visit to the internal node, or the value leaf if this is the single visit to a leaf
node. (These symbols are defined in <search.h>.) The third argument is the depth of the node; the root
node has depth zero.
(Más comúnmente, preorder, postorder, y endorder son conocidos como preorder, inorder, and postorder:
antes de visitar los hijos, después del primero y antes del segundo, y después de visitar los hijos. Así,
la elección del nombre postorder es bastante confusa.)
twalk_r() is similar to twalk(), but instead of the depth argument, the closure argument pointer is
passed to each invocation of the action callback, unchanged. This pointer can be used to pass
information to and from the callback function in a thread-safe fashion, without resorting to global
variables.
tdestroy() elimina el árbol entero apuntado por root, liberando todos los recursos reservados por la
función tsearch. Para los datos en cada nodo del árbol se llama a la función free_node. El puntero a
los datos es pasado como argumento a la función. Si esta tarea no es necesaria free_node debe apuntar a
una función que no haga nada.
VALOR DEVUELTO
tsearch() returns a pointer to a matching node in the tree, or to the newly added node, or NULL if there
was insufficient memory to add the item. tfind() returns a pointer to the node, or NULL if no match is
found. If there are multiple items that match the key, the item whose node is returned is unspecified.
tdelete() returns a pointer to the parent of the node deleted, or NULL if the item was not found. If
the deleted node was the root node, tdelete() returns a dangling pointer that must not be accessed.
tsearch(), tfind(), y tdelete() devuelven NULL si rootp es NULL en la entrada a la función.
VERSIONES
twalk_r() is available in glibc since version 2.30.
ATRIBUTOS
Para obtener una explicación de los términos usados en esta sección, véase attributes(7).
┌─────────────────────┬────────────────────┬────────────────────┐
│ Interfaz │ Atributo │ Valor │
├─────────────────────┼────────────────────┼────────────────────┤
│ tsearch(), tfind(), │ Seguridad del hilo │ MT-Safe race:rootp │
│ tdelete() │ │ │
├─────────────────────┼────────────────────┼────────────────────┤
│ twalk() │ Seguridad del hilo │ MT-Safe race:root │
├─────────────────────┼────────────────────┼────────────────────┤
│ twalk_r() │ Seguridad del hilo │ MT-Safe race:root │
├─────────────────────┼────────────────────┼────────────────────┤
│ tdestroy() │ Seguridad del hilo │ Multi-hilo seguro │
└─────────────────────┴────────────────────┴────────────────────┘
CONFORME A
POSIX.1-2001, POSIX.1-2008, SVr4. The functions tdestroy() and twalk_r() are GNU extensions.
NOTAS
twalk() toma un puntero a la raíz, mientra que las otras funciones toman un puntero a una variable que
apunta a la raíz.
tdelete() libera la memoria necesaria para el elemento en el árbol. El usuario es el responsable de
liberar la memoria de los correspondientes datos.
El programa de ejemplo depende del hecho de que twalk() no vuelve a referenciar a un nodo después de
llamar a la función de usuario con el argumento "endorder" o "leaf". Esto funciona con la biblioteca de
GNU, pero no está en la documentación System V.
EJEMPLOS
El ejemplo siguiente inserta doce números aleatorios en un árbol binario, donde los números duplicados se
meten hacia abajo, e imprime los números en orden.
#define _GNU_SOURCE /* Expose declaration of tdestroy() */
#include <search.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
static void *root = NULL;
static void *
xmalloc(size_t n)
{
void *p;
p = malloc(n);
if (p)
return p;
fprintf(stderr, "insufficient memory\n");
exit(EXIT_FAILURE);
}
static int
compare(const void *pa, const void *pb)
{
if (*(int *) pa < *(int *) pb)
return -1;
if (*(int *) pa > *(int *) pb)
return 1;
return 0;
}
static void
action(const void *nodep, VISIT which, int depth)
{
int *datap;
switch (which) {
case preorder:
break;
case postorder:
datap = *(int **) nodep;
printf("%6d\n", *datap);
break;
case endorder:
break;
case leaf:
datap = *(int **) nodep;
printf("%6d\n", *datap);
break;
}
}
int
main(void)
{
int **val;
srand(time(NULL));
for (int i = 0; i < 12; i++) {
int *ptr = xmalloc(sizeof(*ptr));
*ptr = rand() & 0xff;
val = tsearch(ptr, &root, compare);
if (val == NULL)
exit(EXIT_FAILURE);
else if (*val != ptr)
free(ptr);
}
twalk(root, action);
tdestroy(root, free);
exit(EXIT_SUCCESS);
}
VÉASE TAMBIÉN
bsearch(3), hsearch(3), lsearch(3), qsort(3)
COLOFÓN
Esta página es parte de la versión 5.10 del proyecto Linux man-pages. Puede encontrar una descripción del
proyecto, información sobre cómo informar errores y la última versión de esta página en
https://www.kernel.org/doc/man-pages/.
TRADUCCIÓN
La traducción al español de esta página del manual fue creada por Carlos Gomez Romero
<cgomez@databasedm.es> y Miguel Pérez Ibars <mpi79470@alu.um.es>
Esta traducción es documentación libre; lea la GNU General Public License Version 3 o posterior con
respecto a las condiciones de copyright. No existe NINGUNA RESPONSABILIDAD.
Si encuentra algún error en la traducción de esta página del manual, envíe un correo electrónico a
debian-l10n-spanish@lists.debian.org.
GNU 1 Noviembre 2020 TSEARCH(3)