版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bingongzi/article/details/84978797
二叉树排序树或者是一颗空树性质:若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值,若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值,它的左、右子树也分别为二叉排序树,经过中序遍历一颗二叉树时可以得到一个节点的值递增的有序序列。
下面是二叉排序树的创建、插入、中序遍历、计算树的最大高度、查找程序。
代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int date;
node *left;//左孩子
node *right;//右孩子
};
/*void CreatBST(node* &bst)
{//创建随机的二叉排序树
int date;
int n=1000;//生成的二叉树的结点数
node *q,*r;
while(n--)
{
//scanf("%d",&date);
date=rand();//生成随机数
q=new node;//产生新节点
q->date=date;
q->left=NULL;
q->right=NULL;
if(bst==NULL)//说明原来是一个空树
bst=q; //这是生成的第一个结点,就是根
else
{//不是根节点,需要找到q应该在的位置,若已经存在就返回,若不存在就把这个结点挂在bst上
r=new node;
r=bst;
while(1)
{//循环找q所在的位置
if(q->date<r->date&&r->left==NULL)
{
r->left=q;
break;
}
else if(q->date<r->date&&r->left!=NULL)
{
r=r->left;
}
else if(q->date>r->date&&r->right==NULL)
{
r->right=q;
break;
}
else if(q->date>r->date&&r->right!=NULL)
{
r=r->right;
}
if(q->date==r->date)//说明该数字已经存在,不能重复加入
break;
}
}
}
}*/
void Insert(node* &bst,int n)//插入函数
{
if(bst==NULL)
{
node *q=new node;
q->date=n;
q->left=q->right=NULL;
bst=q;
}
else if(n<bst->date)
Insert(bst->left,n);//递归左子树
else if(n>bst->date)
Insert(bst->right,n);//递归右子树
}
void CreatBST(node* &bst)
{//创建已知的二叉排序树
int n;
while(scanf("%d",&n),n!=0)
{
Insert(bst,n);//将此节点插入二叉排序树bst中
}
}
int Search(node* &shu,int key) //查找函数
{
if(shu==NULL)
return 0;
else
{
if(shu->date==key)
return 1;
else if(key<shu->date)
return Search(shu->left,key);
else if(key>shu->date)
return Search(shu->right,key);
}
}
void MidBST(node* &bst)//中序遍历得到从小到大排序
{
if(bst==NULL)
return ;
else
{
MidBST(bst->left);//左
printf("%d ",bst->date);//根
MidBST(bst->right);//右
}
}
int HighBST(node* &bst)//计算树的最大高度
{
int h1,h2;
if(bst==NULL)
return 0;
else
{
h1=HighBST(bst->left);
h2=HighBST(bst->right);
if(h1>h2)
return h1+1;
else
return h2+1;
}
}
int main()
{
node *bst,*shu;
int h,key;
bst=new node;//生成根节点
bst=NULL;
printf("请输入一连串整数,输入0时结束: \n");
CreatBST(bst);
printf("二叉树的中序遍历:\n");
MidBST(bst);//中序遍历二叉排序树
h=HighBST(bst);
printf("\n树的最大高度为:%d\n",h);
shu=new node;
shu=NULL;
shu=bst;
printf("请输入要查找的数:\n");
scanf("%d",&key);
if(Search(shu,key))//查找key
printf("yes\n");
else
printf("no\n");
return 0;
}