二叉排序树生成查找

#include <stdio.h>
#include 
<stdlib.h>

typedef 
struct snode
{
    
int data;
    
struct snode *left, *right;
}
BTree;

void insert(BTree *&s, int x)
{
    
if(s == NULL)
    
{
        s 
= (BTree *)malloc(sizeof(BTree));
        s
->data = x;
        s
->left = NULL;
        s
->right = NULL;
    }

    
else if(s->data == x)
        
return;
    
else if(x < s->data)
        insert(s
->left, x);
    
else
        insert(s
->right, x);
}


BTree 
*creat()
{
    BTree 
*= NULL;
    
while(1)
    
{
        
int x;
        scanf(
"%d"&x);
        
if(x == 0)
            
break;
        
else
            insert(t, x);
    }

    
return t;
}


void preorder(BTree *p)
{
    
if(p != NULL)
    
{
        printf(
"%3d", p->data);
        preorder(p
->left);
        preorder(p
->right);
    }

}


BTree 
*search_num(BTree *t, int x)
{
    
if(t == NULL)
        
return NULL;
    
else
    
{
        
if(t->data == x)
            
return t;
        
else if(x < t->data)
            search_num(t
->left, x);
        
else
            search_num(t
->right, x);
    }

}


int main()
{
    BTree 
*tree;
    printf(
"请输入创建一个排序二叉树的数,以0结束 ");
    tree 
= creat();
    printf(
"先序遍历如下 ");
    preorder(tree);
    printf(
" ");
    printf(
"请输入要查找的数: ");
    
int num;
    scanf(
"%d"&num);
    BTree 
*test = search_num(tree, num);
    
if(test)
        printf(
"找到 ");
    
else
        printf(
"没找到 ");
    
return 0;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值