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
16       void *tfind(const void *key, void *const *rootp,
17                       int (*compar)(const void *, const void *));
18
19       void *tdelete(const void *key, void **rootp,
20                       int (*compar)(const void *, const void *));
21
22       void twalk(const void *root,
23                       void (*action)(const void *nodep, VISIT which,
24                                      int depth));
25
26       #define _GNU_SOURCE         /* See feature_test_macros(7) */
27       #include <search.h>
28
29       void twalk_r(const void *root,
30                       void (*action)(const void *nodep, VISIT which,
31                                      void *closure),
32                       void *closure);
33
34       void tdestroy(void *root, void (*free_node)(void *nodep));
35

DESCRIPTION

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

RETURN VALUE

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

VERSIONS

110       twalk_r() is available in glibc since version 2.30.
111

ATTRIBUTES

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

CONFORMING TO

129       POSIX.1-2001,   POSIX.1-2008,   SVr4.   The  functions  tdestroy()  and
130       twalk_r() are GNU extensions.
131

NOTES

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

EXAMPLES

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

SEE ALSO

221       bsearch(3), hsearch(3), lsearch(3), qsort(3)
222

COLOPHON

224       This  page  is  part of release 5.10 of the Linux man-pages project.  A
225       description of the project, information about reporting bugs,  and  the
226       latest     version     of     this    page,    can    be    found    at
227       https://www.kernel.org/doc/man-pages/.
228
229
230
231GNU                               2020-11-01                        TSEARCH(3)
Impressum