xref: /freebsd/lib/libc/stdlib/twalk.c (revision 7cc42f6d25ef2e19059d088fa7d4853fe9afefb5)
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 __FBSDID("$FreeBSD$");
19 
20 #define _SEARCH_PRIVATE
21 #include <search.h>
22 #include <stdlib.h>
23 
24 typedef void (*cmp_fn_t)(const posix_tnode *, VISIT, int);
25 
26 /* Walk the nodes of a tree */
27 static void
28 trecurse(const posix_tnode *root, cmp_fn_t action, int level)
29 {
30 
31 	if (root->llink == NULL && root->rlink == NULL)
32 		(*action)(root, leaf, level);
33 	else {
34 		(*action)(root, preorder, level);
35 		if (root->llink != NULL)
36 			trecurse(root->llink, action, level + 1);
37 		(*action)(root, postorder, level);
38 		if (root->rlink != NULL)
39 			trecurse(root->rlink, action, level + 1);
40 		(*action)(root, endorder, level);
41 	}
42 }
43 
44 /* Walk the nodes of a tree */
45 void
46 twalk(const posix_tnode *vroot, cmp_fn_t action)
47 {
48 	if (vroot != NULL && action != NULL)
49 		trecurse(vroot, action, 0);
50 }
51