>*p=(tree*)malloc(sizeof(tree));
If you really are using C then there's no good reason to cast malloc. It hides the fact that you forgot to include stdlib.h.
>void main()
main doesn't return void, it never has. It returns int, and nothing else.
>fflush(stdin);
fflush is only defined for output streams, using it with an input stream is wrong.
Here is a much cleaner way to write a binary search tree:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
int search ( struct node *tree, int key )
{
if ( tree == NULL ) {
return 0;
} else if ( key == tree->data ) {
return 1;
} else if ( key < tree->data ) {
return search ( tree->left, key );
} else {
return search ( tree->right, key );
}
}
struct node *insert ( struct node *tree, int key )
{
if ( tree == NULL ) {
tree = malloc ( sizeof *tree );
if ( tree == NULL )
return tree;
tree->data = key;
tree->left = tree->right = NULL;
} else if ( key < tree->data ) {
tree->left = insert ( tree->left, key );
} else {
tree->right = insert ( tree->right, key );
}
return tree;
}
void pretty_print ( struct node *tree, int level )
{
if ( tree == NULL ) {
printf ( "%*s~\n", level * 3, "" );
} else {
pretty_print ( tree->right, level + 1 );
printf ( "%*s%d\n", level * 3, "", tree->data );
pretty_print ( tree->left, level + 1 );
}
}
void inorder_print ( struct node *tree )
{
if ( tree == NULL )
return;
inorder_print ( tree->left );
printf ( "%-4d", tree->data );
inorder_print ( tree->right );
}
int main ( void )
{
struct node *tree = NULL;
int i, n = 0;
for ( i = 0; i < 10; i++ )
tree = insert ( tree, rand() % 100 );
pretty_print ( tree, 0 );
printf ( "\n---------------------------\n" );
inorder_print ( tree );
printf ( "\n---------------------------\n" );
for ( i = 0; i < 100; i++ ) {
if ( search ( tree, i ) != 0 ) {
printf ( "%-4d", i );
++n;
}
}
printf ( "\n%d numbers found", n );
printf ( "\n---------------------------\n" );
getchar();
return 0;
} Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401