二叉排序树的构造和查找

问题描述:

输入一组无序关键字(整数)序列,构造一棵二叉排序树并对其进行中序遍历输出;在二叉排序树中查找某一关键字,若存在,显示查找成功;若不存在,将其插入到二叉排序树中,再中序遍历输出。

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

typedef struct Node{
	int data;
	Node *lchild;
    Node *rchild;
}Node,*Tree;
//二叉树的存储结构

Node *CreateTree(int n){
	Node *p = (Node*)malloc(sizeof(Node));
	p->data = n;
	p->lchild = NULL;
	p->rchild = NULL;
	return p;
}
//创建树

void Insert(Node *&T, int n){
	if(!T)
		T = CreateTree(n);
	else if(n > T->data) 
        Insert(T->rchild, n);//小于在左子树添加
	else            
        Insert(T->lchild, n);//大于在右子树添加
}
//增加元素

void Middle(Tree T){
	if (T)
	{
		if(T->lchild) Middle(T->lchild);
		printf("%d ",T->data);
		if(T->rchild) Middle(T->rchild);
	}
}
//中序遍历输出二叉树

int Search(Tree T, int n){
	if(!T)
		return 0;//树空返回0
	else if(n = T->data) 
        return 1;//相等返回1
	else if(n < T->data)           
        Search(T->lchild, n);//小于查找左子树
    else if(n > T->data)
        Search(T->rchild, n);//大于查找右子树
}
//在二叉排序树中查找元素

int main(){
    Node *T = NULL;//树的头节点
	int n;

    printf("输入一个无序关键字序列,空格分隔,以EOF结束\n");
	while(scanf("%d", &n) != EOF)
		Insert(T, n);
    //获取用户输入,创建树

    printf("中序遍历二叉排序树:\n");
	Middle(T);
    //输出中序遍历

    printf("\n输入你要查找的数:\n");
    scanf("%d", &n);
    if(Search(T, n)) 
        printf("这个数在树中\n");//找到这个数
    else
    {
        printf("无此数,将数添加到树,再输出中序遍历\n");
        Insert(T, n);//没找到,插入到树
        Middle(T);//再次遍历输出
    }
    
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哆啦叮当

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值