xref: /freebsd/lib/libc/stdlib/twalk.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*	$NetBSD: twalk.c,v 1.4 2012/03/20 16:38:45 matt Exp $	*/
2 
3 /*
4  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
5  * the AT&T man page says.
6  *
7  * Written by reading the System V Interface Definition, not the code.
8  *
9  * Totally public domain.
10  */
11 
12 #include <sys/cdefs.h>
13 #if 0
14 #if defined(LIBC_SCCS) && !defined(lint)
15 __RCSID("$NetBSD: twalk.c,v 1.4 2012/03/20 16:38:45 matt Exp $");
16 #endif /* LIBC_SCCS and not lint */
17 #endif
18 #define _SEARCH_PRIVATE
19 #include <search.h>
20 #include <stdlib.h>
21 
22 typedef void (*cmp_fn_t)(const posix_tnode *, VISIT, int);
23 
24 /* Walk the nodes of a tree */
25 static void
26 trecurse(const posix_tnode *root, cmp_fn_t action, int level)
27 {
28 
29 	if (root->llink == NULL && root->rlink == NULL)
30 		(*action)(root, leaf, level);
31 	else {
32 		(*action)(root, preorder, level);
33 		if (root->llink != NULL)
34 			trecurse(root->llink, action, level + 1);
35 		(*action)(root, postorder, level);
36 		if (root->rlink != NULL)
37 			trecurse(root->rlink, action, level + 1);
38 		(*action)(root, endorder, level);
39 	}
40 }
41 
42 /* Walk the nodes of a tree */
43 void
44 twalk(const posix_tnode *vroot, cmp_fn_t action)
45 {
46 	if (vroot != NULL && action != NULL)
47 		trecurse(vroot, action, 0);
48 }
49