1TSEARCH(3)                 Linux Programmer's Manual                TSEARCH(3)
2
3
4

NAME

6       tsearch, tfind, tdelete, twalk, tdestroy - manage a binary search tree
7

SYNOPSIS

9       #include <search.h>
10
11       typedef enum { preorder, postorder, endorder, leaf } VISIT;
12
13       void *tsearch(const void *key, void **rootp,
14                       int (*compar)(const void *, const void *));
15       void *tfind(const void *key, void *const *rootp,
16                       int (*compar)(const void *, const void *));
17       void *tdelete(const void *restrict key, void **restrict rootp,
18                       int (*compar)(const void *, const void *));
19       void twalk(const void *root,
20                       void (*action)(const void *nodep, VISIT which,
21                                      int depth));
22
23       #define _GNU_SOURCE         /* See feature_test_macros(7) */
24       #include <search.h>
25
26       void twalk_r(const void *root,
27                       void (*action)(const void *nodep, VISIT which,
28                                      void *closure),
29                       void *closure);
30       void tdestroy(void *root, void (*free_node)(void *nodep));
31

DESCRIPTION

33       tsearch(), tfind(), twalk(), and tdelete() manage a binary search tree.
34       They are generalized from Knuth (6.2.2) Algorithm T.  The  first  field
35       in  each  node of the tree is a pointer to the corresponding data item.
36       (The calling program must store the actual data.)  compar points  to  a
37       comparison  routine,  which takes pointers to two items.  It should re‐
38       turn an integer which is negative,  zero,  or  positive,  depending  on
39       whether the first item is less than, equal to, or greater than the sec‐
40       ond.
41
42       tsearch() searches the tree for an item.  key points to the item to  be
43       searched  for.   rootp points to a variable which points to the root of
44       the tree.  If the tree is empty, then the variable that rootp points to
45       should  be  set  to  NULL.   If  the  item  is  found in the tree, then
46       tsearch() returns a pointer to the corresponding tree node.  (In  other
47       words,  tsearch() returns a pointer to a pointer to the data item.)  If
48       the item is not found, then tsearch() adds it, and returns a pointer to
49       the corresponding tree node.
50
51       tfind()  is  like tsearch(), except that if the item is not found, then
52       tfind() returns NULL.
53
54       tdelete() deletes an item from the tree.  Its arguments are the same as
55       for tsearch().
56
57       twalk() performs depth-first, left-to-right traversal of a binary tree.
58       root points to the starting node for the traversal.  If  that  node  is
59       not  the  root,  then  only  part of the tree will be visited.  twalk()
60       calls the user function action each time a node is  visited  (that  is,
61       three  times  for  an  internal node, and once for a leaf).  action, in
62       turn, takes three arguments.  The first argument is a  pointer  to  the
63       node  being  visited.  The structure of the node is unspecified, but it
64       is possible to cast the pointer to a  pointer-to-pointer-to-element  in
65       order  to  access  the element stored within the node.  The application
66       must not modify the structure pointed to by this argument.  The  second
67       argument  is  an  integer  which takes one of the values preorder, pos‐
68       torder, or endorder depending on whether this is the first, second,  or
69       third visit to the internal node, or the value leaf if this is the sin‐
70       gle visit to a leaf node.  (These symbols are defined  in  <search.h>.)
71       The  third  argument  is the depth of the node; the root node has depth
72       zero.
73
74       (More commonly, preorder, postorder, and endorder  are  known  as  pre‐
75       order,  inorder, and postorder: before visiting the children, after the
76       first and before the second, and after visiting  the  children.   Thus,
77       the choice of name postorder is rather confusing.)
78
79       twalk_r() is similar to twalk(), but instead of the depth argument, the
80       closure argument pointer is passed to each  invocation  of  the  action
81       callback,  unchanged.   This pointer can be used to pass information to
82       and from the callback function in a thread-safe  fashion,  without  re‐
83       sorting to global variables.
84
85       tdestroy()  removes  the whole tree pointed to by root, freeing all re‐
86       sources allocated by the tsearch() function.  For the data in each tree
87       node  the  function  free_node  is  called.  The pointer to the data is
88       passed as the argument to the function.  If no such work is  necessary,
89       free_node must point to a function doing nothing.
90

RETURN VALUE

92       tsearch()  returns  a pointer to a matching node in the tree, or to the
93       newly added node, or NULL if there was insufficient memory to  add  the
94       item.   tfind()  returns  a pointer to the node, or NULL if no match is
95       found.  If there are multiple items that match the key, the item  whose
96       node is returned is unspecified.
97
98       tdelete()  returns a pointer to the parent of the node deleted, or NULL
99       if the item was not found.  If the deleted  node  was  the  root  node,
100       tdelete() returns a dangling pointer that must not be accessed.
101
102       tsearch(), tfind(), and tdelete() also return NULL if rootp was NULL on
103       entry.
104

VERSIONS

106       twalk_r() is available in glibc since version 2.30.
107

ATTRIBUTES

109       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
110       tributes(7).
111
112       ┌─────────────────────────────────┬───────────────┬────────────────────┐
113Interface                        Attribute     Value              
114       ├─────────────────────────────────┼───────────────┼────────────────────┤
115tsearch(), tfind(), tdelete()    │ Thread safety │ MT-Safe race:rootp │
116       ├─────────────────────────────────┼───────────────┼────────────────────┤
117twalk()                          │ Thread safety │ MT-Safe race:root  │
118       ├─────────────────────────────────┼───────────────┼────────────────────┤
119twalk_r()                        │ Thread safety │ MT-Safe race:root  │
120       ├─────────────────────────────────┼───────────────┼────────────────────┤
121tdestroy()                       │ Thread safety │ MT-Safe            │
122       └─────────────────────────────────┴───────────────┴────────────────────┘
123

CONFORMING TO

125       POSIX.1-2001,   POSIX.1-2008,   SVr4.   The  functions  tdestroy()  and
126       twalk_r() are GNU extensions.
127

NOTES

129       twalk() takes a pointer to the root, while the other functions  take  a
130       pointer to a variable which points to the root.
131
132       tdelete() frees the memory required for the node in the tree.  The user
133       is responsible for freeing the memory for the corresponding data.
134
135       The example program depends on the fact that twalk() makes  no  further
136       reference  to a node after calling the user function with argument "en‐
137       dorder" or "leaf".  This works with the GNU library implementation, but
138       is not in the System V documentation.
139

EXAMPLES

141       The following program inserts twelve random numbers into a binary tree,
142       where duplicate numbers are collapsed, then prints the numbers  in  or‐
143       der.
144
145       #define _GNU_SOURCE     /* Expose declaration of tdestroy() */
146       #include <search.h>
147       #include <stddef.h>
148       #include <stdlib.h>
149       #include <stdio.h>
150       #include <time.h>
151
152       static void *root = NULL;
153
154       static void *
155       xmalloc(size_t n)
156       {
157           void *p;
158           p = malloc(n);
159           if (p)
160               return p;
161           fprintf(stderr, "insufficient memory\n");
162           exit(EXIT_FAILURE);
163       }
164
165       static int
166       compare(const void *pa, const void *pb)
167       {
168           if (*(int *) pa < *(int *) pb)
169               return -1;
170           if (*(int *) pa > *(int *) pb)
171               return 1;
172           return 0;
173       }
174
175       static void
176       action(const void *nodep, VISIT which, int depth)
177       {
178           int *datap;
179
180           switch (which) {
181           case preorder:
182               break;
183           case postorder:
184               datap = *(int **) nodep;
185               printf("%6d\n", *datap);
186               break;
187           case endorder:
188               break;
189           case leaf:
190               datap = *(int **) nodep;
191               printf("%6d\n", *datap);
192               break;
193           }
194       }
195
196       int
197       main(void)
198       {
199           int **val;
200
201           srand(time(NULL));
202           for (int i = 0; i < 12; i++) {
203               int *ptr = xmalloc(sizeof(*ptr));
204               *ptr = rand() & 0xff;
205               val = tsearch(ptr, &root, compare);
206               if (val == NULL)
207                   exit(EXIT_FAILURE);
208               else if (*val != ptr)
209                   free(ptr);
210           }
211           twalk(root, action);
212           tdestroy(root, free);
213           exit(EXIT_SUCCESS);
214       }
215

SEE ALSO

217       bsearch(3), hsearch(3), lsearch(3), qsort(3)
218

COLOPHON

220       This  page  is  part of release 5.12 of the Linux man-pages project.  A
221       description of the project, information about reporting bugs,  and  the
222       latest     version     of     this    page,    can    be    found    at
223       https://www.kernel.org/doc/man-pages/.
224
225
226
227GNU                               2021-03-22                        TSEARCH(3)
Impressum