>Might want to check out Prelude's Binary Tree Tutorial here for some code to look at
Better yet, check out the updated and improved version on my website.
>I know I will have to cast values and use void pointers, but I am unsure how to go about this.
The concept is simple. Your tree assumes nothing and only works with nodes. You can pass a function that compares items:
Code:
struct node {
void *data;
struct node *left, *right;
};
struct tree {
struct node *root;
int (*compare) ( const void *a, const void *b );
};
If you don't mind me posting some quick and dirty code, here is the concept:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
void *data;
struct node *left, *right;
};
struct tree {
struct node *root;
int (*compare) ( const void *a, const void *b );
};
struct node *insert_r ( struct node *root,
struct node *item, int (*cmp) ( const void *a, const void *b ) )
{
if ( root == NULL )
root = item;
else if ( cmp ( item->data, root->data ) < 0 )
root->left = insert_r ( root->left, item, cmp );
else
root->right = insert_r ( root->right, item, cmp );
return root;
}
void insert ( struct tree *tree, struct node *item )
{
tree->root = insert_r ( tree->root, item, tree->compare );
}
void print ( struct node *root, int level )
{
int i;
if ( root == NULL ) {
for ( i = 0; i < level; i++ )
printf ( "\t" );
printf ( "~\n" );
}
else {
print ( root->right, level + 1 );
for ( i = 0; i < level; i++ )
printf ( "\t" );
printf ( "%s", (char *)root->data );
print ( root->left, level + 1 );
}
}
char *dupstr ( const char *s )
{
char *ret = malloc ( strlen ( s ) + 1 );
if ( ret == NULL )
return NULL;
return strcpy ( ret, s );
}
int compare ( const void *a, const void *b )
{
return strcmp ( (const char *)a, (const char *)b );
}
int main ( void )
{
struct tree t = {0, &compare};
struct node *item;
char buffer[BUFSIZ];
while ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
item = malloc ( sizeof *item );
item->data = dupstr ( buffer );
item->left = item->right = NULL;
insert ( &t, item );
}
print ( t.root, 0 );
}