//构造一颗二叉树,输出其先序、中序、后序遍历序列,再求二叉树结点总数、叶子结点数、深度
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW -2
#define ERROR 0
typedef char TElemType;
typedef int Status;
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status CreateBiTree(BiTree&T){
char ch;
scanf("%c",&ch);
if(ch==‘#‘) T=NULL;
else{
if(!(T=(BiTNode*)malloc(sizeof(BiTNode))))
exit(OVERFLOW);
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
return OK;
}//创建二叉树
void PreOrderTraverse(BiTree T){
if(T){
printf("%c",T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
} //先序
void MidOrderTraverse(BiTree T){
if(T){
MidOrderTraverse(T->lchild);
printf("%c",T->data);
MidOrderTraverse(T->rchild);
}
} //中序
void PostOrderTraverse(BiTree T){
if(T){
PostOrderTraverse(T->lchild);
PostOrderTraverse(T->rchild);
printf("%c",T->data);
}
} //后序
int NodeCount(BiTree T){
if(T==NULL)
return 0;
else
return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
} //统计二叉树的结点总数
int LeafCount(BiTree T){
if(T==NULL)
return 0;
if(T->lchild==NULL&&T->rchild==NULL)
return 1;
else
return LeafCount(T->lchild)+LeafCount(T->rchild);
}//统计叶子结点个数
int Depth(BiTree T){
int depthval,depthL,depthR;
if(!T) depthval=0;
else{
depthL=Depth(T->lchild);
depthR=Depth(T->rchild);
depthval=1+(depthL>depthR?depthL:depthR);
}
return depthval;
} //计算深度
int main(){
int NodeCounts,LeafCounts,depth;
BiTree T;
printf("请输入二叉树结点:\n");
CreateBiTree(T);
printf("\n先序输出:");
PreOrderTraverse(T);
printf("\n中序输出:");
MidOrderTraverse(T);
printf("\n后序输出:");
PostOrderTraverse(T);
NodeCounts=NodeCount(T);
printf("\n统计二叉树的结点总数为:%d",NodeCounts);
LeafCounts=LeafCount(T);
printf("\n统计二叉树的叶子结点个数为:%d",LeafCounts);
depth=Depth(T);
printf("\n二叉树的深度为:%d",depth);
}