二叉树创建&判断是否有序二叉树&树的深度

来源:互联网 发布:汽车防盗芯片编程器 编辑:程序博客网 时间:2024/04/28 23:05
#include<stdio.h>#include<stdlib.h>#define max 10#define MAX(a,b) ( a > b ? a : b )typedef struct node{int data;node *lchild,*rchild;}Bitree;Bitree *B[max];int temp=0;int Btree[max];Bitree *Creatree(){    //建立二叉树Bitree *T,*S;int ch;int front,rear,sign;sign=0;front=0;rear=-1;T=NULL;printf("建立二叉树(1表示虚结点,0表示输入结束):\n");scanf("%d",&ch);while(ch!=0){ if(ch!=1){    //输入结点不是虚结点S=(Bitree *)malloc(sizeof(Bitree));S->data=ch;S->lchild=S->rchild=NULL;rear++;B[rear]=S;if(rear==front){T=S;sign++;}else{if(sign%2==1)  //寻找父结点B[front]->lchild=S;   if(sign%2==0){B[front]->rchild=S;front++;}sign++;}}else{        //输入结点为虚结点if(sign%2==0)front++;sign++;}scanf("%d",&ch);}return T;}void Inorder(Bitree *T){     //中序遍历二叉树,并将每个结点数据存入数组中if(T!=NULL){Inorder(T->lchild);printf("%d\t",T->data);Btree[temp]=T->data;temp++;Inorder(T->rchild);}}int Judgesort_bitree(int Btree[]){    //判断是否是二叉树int i,sign=1;for(i=0;i<temp-1;i++){if(Btree[i]>Btree[i+1]){sign=0;break;}}return sign;}void Judgeout(int a){   //判断输出if(a==1)printf("给定二叉树是二叉排序树!\n");if(a==0)printf("给定二叉树不是二叉排序树!\n");}int getBitTreeDeep(Bitree *T){//判断树的度 if( T==NULL )return 0;return ( MAX( getBitTreeDeep( T->lchild) , getBitTreeDeep( T->rchild ) ) + 1 );}int main(){Bitree *T;T=Creatree();//创建树 printf("中序遍历:\n");Inorder(T);printf("\n");Judgeout(Judgesort_bitree(Btree));//判断是否二叉排序树 printf("树的度:\n");printf("%d\n",getBitTreeDeep(T));//输出树的度 return 0;}

原创粉丝点击