二叉搜索树

二叉搜索树是一棵二叉树,它的每个内部节点都关联一个关键字,并具有以下性质:任意节点的关键字大于或等于该节点左子树中所有节点的关键字,小于等于该节点右子树中所有节点的关键字。

实现:

#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;

}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值