xref: /minix3/lib/libc/stdlib/twalk.c (revision f14fb602092e015ff630df58e17c2a9cd57d29b3)
1*f14fb602SLionel Sambuc /*	$NetBSD: twalk.c,v 1.4 2012/03/20 16:38:45 matt Exp $	*/
22fe8fb19SBen Gras 
32fe8fb19SBen Gras /*
42fe8fb19SBen Gras  * Tree search generalized from Knuth (6.2.2) Algorithm T just like
52fe8fb19SBen Gras  * the AT&T man page says.
62fe8fb19SBen Gras  *
72fe8fb19SBen Gras  * The node_t structure is for internal use only, lint doesn't grok it.
82fe8fb19SBen Gras  *
92fe8fb19SBen Gras  * Written by reading the System V Interface Definition, not the code.
102fe8fb19SBen Gras  *
112fe8fb19SBen Gras  * Totally public domain.
122fe8fb19SBen Gras  */
132fe8fb19SBen Gras 
142fe8fb19SBen Gras #include <sys/cdefs.h>
152fe8fb19SBen Gras #if defined(LIBC_SCCS) && !defined(lint)
16*f14fb602SLionel Sambuc __RCSID("$NetBSD: twalk.c,v 1.4 2012/03/20 16:38:45 matt Exp $");
172fe8fb19SBen Gras #endif /* LIBC_SCCS and not lint */
182fe8fb19SBen Gras 
192fe8fb19SBen Gras #include <assert.h>
202fe8fb19SBen Gras #define _SEARCH_PRIVATE
212fe8fb19SBen Gras #include <search.h>
222fe8fb19SBen Gras #include <stdlib.h>
232fe8fb19SBen Gras 
24*f14fb602SLionel Sambuc typedef void (*cmp_fn_t)(const void *, VISIT, int);
252fe8fb19SBen Gras 
262fe8fb19SBen Gras /* Walk the nodes of a tree */
272fe8fb19SBen Gras static void
trecurse(const node_t * root,cmp_fn_t action,int level)28*f14fb602SLionel Sambuc trecurse(const node_t *root,	/* Root of the tree to be walked */
29*f14fb602SLionel Sambuc 	cmp_fn_t action, int level)
302fe8fb19SBen Gras {
312fe8fb19SBen Gras 	_DIAGASSERT(root != NULL);
322fe8fb19SBen Gras 	_DIAGASSERT(action != NULL);
332fe8fb19SBen Gras 
342fe8fb19SBen Gras 	if (root->llink == NULL && root->rlink == NULL)
352fe8fb19SBen Gras 		(*action)(root, leaf, level);
362fe8fb19SBen Gras 	else {
372fe8fb19SBen Gras 		(*action)(root, preorder, level);
382fe8fb19SBen Gras 		if (root->llink != NULL)
392fe8fb19SBen Gras 			trecurse(root->llink, action, level + 1);
402fe8fb19SBen Gras 		(*action)(root, postorder, level);
412fe8fb19SBen Gras 		if (root->rlink != NULL)
422fe8fb19SBen Gras 			trecurse(root->rlink, action, level + 1);
432fe8fb19SBen Gras 		(*action)(root, endorder, level);
442fe8fb19SBen Gras 	}
452fe8fb19SBen Gras }
462fe8fb19SBen Gras 
472fe8fb19SBen Gras /* Walk the nodes of a tree */
482fe8fb19SBen Gras void
twalk(const void * vroot,cmp_fn_t action)49*f14fb602SLionel Sambuc twalk(const void *vroot, cmp_fn_t action) /* Root of the tree to be walked */
502fe8fb19SBen Gras {
512fe8fb19SBen Gras 	if (vroot != NULL && action != NULL)
522fe8fb19SBen Gras 		trecurse(vroot, action, 0);
532fe8fb19SBen Gras }
54