//测试结点abd###ce##f##
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLENGTH 30
typedef struct Binode{
char data;
struct Binode *lchild;
struct Binode *rchild;
}Binode,*Bintree;
Bintree t=NULL;
int n=0;
int n2=0;
int d1=0,d2=0,max=0;
void CreateBintree(Bintree *t ){//先序创建二叉树
char ch=0;
if((ch=getchar())=='#') {
*t=NULL;
}
else{
*t=(Binode*)malloc(sizeof(Binode));
(*t)->data=ch;
CreateBintree(&(*t)->lchild);
CreateBintree(&(*t)->rchild);
}
}
void PreBintree(Bintree t){//先序遍历
if(t==NULL) return;
else{
printf("%c",t->data);
PreBintree(t->lchild);
PreBintree(t->rchild);
}
}
void MidBintree(Bintree t){//中序遍历
if(t==NULL) return;
else{
MidBintree(t->lchild);
printf("%c",t->data);
MidBintree(t->rchild);
}
}
void LastBintree(Bintree t){//后序遍历
if(t==NULL) return;
else{
LastBintree(t->lchild);
LastBintree(t->rchild);
printf("%c",t->data);
}
}
void LevelBintree(Bintree t){//层次遍历
int i,j;
Bintree q[MAXLENGTH];
Bintree p;
p=t;
if(p!=NULL){
i=0;q[i]=p;j=1;
}
while(i!=j){
p=q[i];
printf("%c",p->data);
if(p->lchild!=NULL){
q[j]=p->lchild;j++;
}
if(p->rchild!=NULL){
q[j]=p->rchild;j++;
}
i++;
}
}
int LeafCount(Bintree t){//输出叶子结点个数
if(t==NULL) return 0;
else{
if(t->lchild==NULL&&t->rchild==NULL){
n++;
}
LeafCount(t->lchild);
LeafCount(t->rchild);
return n;
}
}
void LeafNode(Bintree t){//输出叶子结点
if(t==NULL) return;
else{
if(t->lchild==NULL&&t->rchild==NULL){
printf("%c",t->data);
}
LeafNode(t->lchild);
LeafNode(t->rchild);
}
}
int DeepthBinTree(Bintree t){//树的深度
if(t==NULL) return 0;
else{
d1=DeepthBinTree(t->lchild);
d2=DeepthBinTree(t->rchild);
max=d1>d2?d1:d2;
return max+1;
}
}
int NodeNo(Bintree t){//输出结点个数
if(t==NULL) return 0;
else{
if(t->data!='#'){
n2++;
}
NodeNo(t->lchild);
NodeNo(t->rchild);
return n2;
}
}
int main(void){
int i=1;int x=0;int y=0;
while(i){
printf(" 欢迎来到树的操作程序
");
printf(" 1.创建树
");
printf(" 2.遍历树
");
printf(" 3.求叶子节点个数
");
printf(" 4.输出根节点
");
printf(" 5.输出树的深度
");
printf(" 6.输出树的结点个数
");
printf(" 0.EXIT
");
printf("请输入你要进行的操作
");
fflush(stdin);
scanf("%d",&x);
switch(x){
case 1:
printf("请输入创建的树的结点(空节点请输入#):
");
fflush(stdin);
CreateBintree(&t);
printf("树创建完毕:
");
break;
case 2:
printf("1.先序遍历
");
printf("2.中序遍历
");
printf("3.后序遍历
");
printf("4.层次遍历
");
printf("请选择你的操作
");
scanf("%d",&y);
switch(y){
case 1:PreBintree(t);printf("
");break;
case 2:MidBintree(t);printf("
");break;
case 3:LastBintree(t);printf("
");break;
case 4:LevelBintree(t);printf("
");break;
}
break;
case 3:
printf("树的叶子结点个数为%d
",LeafCount(t));
printf("
");
break;
case 4:
printf("树的叶子结点如下:
");
LeafNode(t);
printf("
");
break;
case 5:
printf("树的深度为%d
",DeepthBinTree(t));
printf("
");
break;
case 6:
printf("树的结点个数为%d
",NodeNo(t));
printf("
");
break;
case 0:
i=0;
break;
}
}
return 0;
}