栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言:二叉排序树的操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言:二叉排序树的操作

实现的功能:

------------------
1、建立二叉排序树
2、输出中序遍历结果
3、查找数据
0、退出
------------------

代码:
#include 
#include 
typedef struct BiNode{
    int  data;
    struct BiNode *lchild;
    struct BiNode *rchild;
}BiNode,*BiTree;
BiTree InsertBST(BiTree T,int e)//二叉树的插入
{
	BiTree s;
	if(!T)
    {
        s=(BiTree)malloc(sizeof(BiNode));
        s->data=e;
	    s->lchild=s->rchild=NULL;
	    T=s;
    }


	else if(edata)
        T->lchild=InsertBST(T->lchild,e);

	else if(e>T->data)
		T->rchild=InsertBST(T->rchild,e);
    return T;
}



BiTree CreatBST(BiTree T)//建立二叉排序树
{
	int e,n,i;
	printf("输入数字的个数:");
    scanf("%d",&n);
    printf("请输入每个数字(空格隔开):");
	for(i=0;ilchild);
        printf("%d ",T->data);
        InOrder(T->rchild);
    }

}

int Search(BiTree T,int key)//查找
{
	BiTree p;
	int x=0;
	p=T;
	while(p)
	{
		if(keydata)
        {
            p=p->lchild;
            ++x;
        }

		else if(key>p->data)
        {
            p=p->rchild;
            ++x;
        }

		else
		{
			printf("数字%d查找成功。n",key);
			printf("数字%d的查找长度为%dn",key,x+1);
			return 1;
		}
	}
	printf("未找到数据%d。n",key);
   // printf("数字%d的查找长度为%dn",key,x+1);
	return 0;
}



int main()
{
	BiTree T=NULL;
	int n,key,selet;
	printf("------------------n");
    printf("1、建立二叉排序树n");
    printf("2、输出中序遍历结果n");
    printf("3、查找数据n");
    printf("0、退出n");
    printf("------------------n");
	while(1)
	{
        printf("n");
        printf("请选择操作:");
        scanf("%d",&selet);
		switch(selet)
		{
			case 1:
				T=CreatBST(T);
				printf("二叉排序树建立成功!n");
				break;
			case 2:
				printf("中序遍历结果为:");
				InOrder(T);
				putchar('n');
				break;
			case 3:
				printf("请输入查找的关键字:");
				scanf("%d",&key);
				Search(T,key);
				break;
            case 0:
                exit(0);
		}
	}
}

结果演示:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/312005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号