二叉排序树的查找

#include<stdio.h>
#include<stdlib.h>
//声明
typedef struct node
{
  int data;
  struct node*left;
  struct node*right;
}BTnode;

//先生成一颗二叉排序树
BTnode* CreateTree(BTnode* root,int x)
{
    if(!root)  //如果root结点为空,创建叶子结点
    {
        root=(BTnode*)malloc(sizeof(BTnode));
        root->data = x;
        root->left=root->right=NULL;
    }else
    {
        if(root->data>x) 
            root->left = CreateTree(root->left,x);  //递归调用左
        else if(root->data<x)
            root->right = CreateTree(root->right,x);//递归调用右
    }
    return root;
}

//中序遍历
void Inorder(BTnode* root)
{
  if(root){
      Inorder(root->left);
      printf("%3d",root->data);
      Inorder(root->right);
  }
}

//查找输出数据
BTnode* query(BTnode* root, int key){
    if(root&&root->data==key){
        return root;
    }else if(key <root->data ){
        return query(root->left,key);
    }else{
        return query(root->right,key);
    }
}

//主函数
int main (void){
    BTnode * root = NULL;
    int x;    //当前数据
    int n;    //数据个数
    int i;    //循环变量
    int key;    //输入的待查询的数据
    printf("请输入n=");
    scanf("%d",&n);
    printf("请输入二叉树的结点data:\n");
    //循环数据生成一颗二叉排序树
    for(i=0;i<n;i++)
    {
        scanf("%d",&x);
        root = CreateTree(root,x);
    }
    //中序遍历
    printf("中序遍历为:");
    Inorder(root);
    printf("\n");
    printf("请输入要查询的数据:\n");
    scanf("%d",&key);
    root = query(root,key);
    if(root){
        printf("所查询的值%d",root->data);    
    }else{
        printf("没有此值");
    }    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值