This is some sample code:
#include <search.h>
#define nKeys ((int)(sizeof(keys)/sizeof(int)))
int __cdecl MyCmp(const void *elem1, const void *elem2)
{
return *((int *)(elem1)) - *((int *)(elem2));
}
static int min = 10000;
static int max = -10000;
char *sVisit[] = {"preorder ",
"postorder",
"endorder ",
"leaf "};
void __cdecl FindMinMax(const void *elem, _VISIT visit, int level)
{
printf("\n[el=% .4d, visit=%s, lev=%d]", **((int **)elem), sVisit[visit], level);
if ((visit == _leaf ||visit == _preorder) && elem)
{
if (**((int **)elem)>= max)
max = **((int **)elem);
if (**((int **)elem)<= min)
min = **((int **)elem);
}
}
void PrintData(int *keys, void **proot, int n)
{
printf("Checking data... ");
for (int i=0; i<n; i++)
{
void *node = _tfind((void *)&keys[i], proot, MyCmp);
if (node)
printf("%d ", **((int **)node));
}
printf("\n");
}
int main(int argc, char *argv[])
{
int keys[] = { 5, -1, 3, -14, 8, 10, 9, 6 };
void *root = NULL;
printf("Inserting data... ");
for (int i=0; i<nKeys; i++)
{
if (_tsearch((void *)&keys[i], &root, MyCmp))
printf ("%d ", keys[i]);
else
printf("\nError!\n");
}
printf("\n");
PrintData(keys, &root, nKeys);
printf("Deleting data... ");
printf ("%d ", **((int **)_tdelete ((void *)&keys[0], &root, MyCmp)));
printf ("%d ", **((int **)_tdelete ((void *)&keys[1], &root, MyCmp)));
printf("\n");
PrintData(keys, &root, nKeys);
printf("Walking data... ");
_twalk(root, FindMinMax);
printf("\n");
printf("Minimum element is %d\n", min);
printf("Maximum element is %d\n", max);
}
EDIT: Improved version