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  * The node_t structure is for internal use only, lint doesn't grok it.
8  *
9  * Written by reading the System V Interface Definition, not the code.
10  *
11  * Totally public domain.
12  */
13 
14 #include <sys/cdefs.h>
15 #if defined(LIBC_SCCS) && !defined(lint)
16 __RCSID("$NetBSD: twalk.c,v 1.4 2012/03/20 16:38:45 matt Exp $");
17 #endif /* LIBC_SCCS and not lint */
18 
19 #include <assert.h>
20 #define _SEARCH_PRIVATE
21 #include <search.h>
22 #include <stdlib.h>
23 
24 typedef void (*cmp_fn_t)(const void *, VISIT, int);
25 
26 /* Walk the nodes of a tree */
27 static void
trecurse(const node_t * root,cmp_fn_t action,int level)28 trecurse(const node_t *root,	/* Root of the tree to be walked */
29 	cmp_fn_t action, int level)
30 {
31 	_DIAGASSERT(root != NULL);
32 	_DIAGASSERT(action != NULL);
33 
34 	if (root->llink == NULL && root->rlink == NULL)
35 		(*action)(root, leaf, level);
36 	else {
37 		(*action)(root, preorder, level);
38 		if (root->llink != NULL)
39 			trecurse(root->llink, action, level + 1);
40 		(*action)(root, postorder, level);
41 		if (root->rlink != NULL)
42 			trecurse(root->rlink, action, level + 1);
43 		(*action)(root, endorder, level);
44 	}
45 }
46 
47 /* Walk the nodes of a tree */
48 void
twalk(const void * vroot,cmp_fn_t action)49 twalk(const void *vroot, cmp_fn_t action) /* Root of the tree to be walked */
50 {
51 	if (vroot != NULL && action != NULL)
52 		trecurse(vroot, action, 0);
53 }
54