#include<stdio.h>
#include<stdlib.h>
typedef struct BiTNode
{
int data;
struct BiTNode *lchild,*rchild;//,*parant;
}BNode,*BTree;
int cDepth(BTree t);
void initVertex(int *a,int *num)
{
int i=0;
printf("how many numbers in the vertex?\n");
scanf("%d",num);
for(i=0;i<*num;i++)
{
printf("Please enter vertex[%d]:\n",i);
scanf("%d",a+i);
}
printf("initedVertex!\n");
}
void insertBTree(BTree &t,int n)
{
if(t==NULL)
{
t=(BTree)malloc(sizeof(BNode));
t->data=n;
t->lchild=t->rchild=NULL;
return ;
}
else if(t->data==n)
return ;// Found return false
else if(n<t->data)
{
insertBTree(t->lchild,n);
return ;
}
else if(n>t->data)
{
insertBTree(t->rchild,n);
return ;
}
}
int searchBTree(BTree &t,int n)
{
if(t==NULL)
{
printf("%d is not existed in the vertex\n",n);
return 0;
}
if(t->data==n)
{
printf("%d is existed in the vertex\n",n);
return 1;
}
if(n<t->data)
{
return searchBTree(t->lchild,n);
}
if(n>t->data)
{
return searchBTree(t->rchild,n);
}
}
//中序排列
void inorder(BTree t)
{
if(t!=NULL)
{
inorder(t->lchild);
printf("%d",t->data);
inorder(t->rchild);
}
}
bool isBalanced(BTree t)
{
if(t==NULL)
return true;
int l=cDepth(t->lchild);
int r=cDepth(t->rchild);
int bf=l-r;
if(bf>1||bf<-1)
return false;
return (isBalanced(t->lchild)&&isBalanced(t->rchild));
}
//想不到啊,这样就能求而二叉树某点深度depth
int cDepth(BTree t)
{
if(t==NULL)
return 0;
int ldepth=cDepth(t->lchild);
int rdepth=cDepth(t->rchild);
return (ldepth>rdepth?ldepth+1:rdepth+1);
}
int main()
{
//init
BTree t=NULL;
int i,j;
int a[100],num;
/* searchBTree(t,5);
if(isBalanced(t))
printf("ball");;
inorder(t);
*/
int choice=-1;
while(true)
{
printf("******************************************************************************************\n");
printf("1:创建排序二叉树\n2:查找\n3:中序输出二叉排序树\n4:判断二叉排序树是否平衡\n5:退出程序\n");
printf("Please enter your choice:\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
initVertex(a,&num);
for(i=0;i<num;i++)
insertBTree(t,a[i]);
printf("******************************************************************************************\n");break;
case 2:
int destination;
printf("Please enter the number that you whant to search:\n");
scanf("%d",&destination);
searchBTree(t,destination);
printf("******************************************************************************************\n");;break;
case 3:
inorder(t);
printf("\n******************************************************************************************\n");
break;
case 4:
if(isBalanced(t))
printf("It is a balanced tree\n");
else
printf("It is not a balanced tree\n");
printf("******************************************************************************************\n");break;
case 5:
return 0;
default:
break;
}
}
return 0;
}
排序二叉树
最新推荐文章于 2022-06-09 09:35:00 发布