二叉搜索树是一棵二叉树,它的每个内部节点都关联一个关键字,并具有以下性质:任意节点的关键字大于或等于该节点左子树中所有节点的关键字,小于等于该节点右子树中所有节点的关键字。
实现:
#include <stdio.h>
#include <stdlib.h>
struct Tree
{
int item;
structTree *l;
structTree *r;
};
void insert_tree( struct Tree** tree, int value )
{
if( *tree== NULL )
{
*tree= ( struct Tree* )malloc(sizeof(struct Tree));
(*tree)->item= value;
(*tree)->l= NULL;
(*tree)->r= NULL;
return;
}
if((*tree)->item<= value )
insert_tree(&((*tree)->r),value);
else
insert_tree(&((*tree)->l),value);
}
void travel( struct Tree * tree )
{
if( tree== NULL )
return;
if(tree->l != NULL)
travel(tree->l );
printf("%d\n",tree->item);
if (tree->r != NULL )
travel(tree->r );
}
void search_tree( struct Tree *tree, int value )
{
if( tree== NULL )
{
printf("cannot find value:%d\n",value);
return;
}
if( tree->item== value )
{
printf("findvalue:%d\n",value);
return;
}
if(tree->item > value )
returnsearch_tree(tree->l, value);
else
returnsearch_tree(tree->r, value);
}
int main( int argc, char* argv[] )
{
structTree* tree = NULL;
insert_tree(&tree,9);
insert_tree(&tree,6);
insert_tree(&tree,10);
insert_tree(&tree,7);
insert_tree(&tree,11);
insert_tree(&tree,8);
insert_tree(&tree,12);
travel(tree);
if( argc== 2 )
{
intvalue = atoi(argv[1]);
search_tree(tree,value);
}
return 0;
}