实验完整代码
#include<stdio.h>
#include<malloc.h>
//二叉树
typedef char datatype;
typedef struct BiTNode{
datatype data;
BiTNode *lchild,*rchild;
}BiTree;
//先序遍历构建二叉树
BiTree *CreateTree(BiTree *bt){
char x;
// printf("请以先序输入树的所有结点值:\n");//输入AB##C##,每次递归读入缓存区一个字符
scanf("%c",&x);
if(x=='#'){
bt=NULL;
}
else{
bt=(BiTree *)malloc(sizeof(BiTree));
bt->data=x;
bt->lchild=CreateTree(bt->lchild);//递归调用先序建树
bt->rchild=CreateTree(bt->rchild);
}
return bt;
}
//先序遍历
void PreOrder(BiTree *bt){
if(bt!=NULL){
printf("%c ",bt->data);
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
//中序遍历
void InOrder(BiTree *bt){
if(bt!=NULL){
InOrder(bt->lchild);
printf("%c ",bt->data);
InOrder(bt->rchild);
}
}
//后序遍历
void PostOrder(BiTree *bt){
if(bt!=NULL){
PostOrder(bt->lchild);
PostOrder(bt->rchild);
printf("%c ",bt->data);
}
}
//求二叉树叶子结点数
void CountLeaf(BiTree *bt,int *x){
if(bt!=NULL){
if(bt->lchild==NULL && bt->rchild==NULL){
(*x)++;
}
CountLeaf(bt->lchild,x);
CountLeaf(bt->rchild,x);
}
}
//求二叉树深度
int Depth(BiTree *bt){
int ldepth,rdepth,maxdepth;
if(bt==NULL){
return 0;
}
ldepth=Depth(bt->lchild);
rdepth=Depth(bt->rchild);
maxdepth=ldepth>rdepth?ldepth+1:rdepth+1;
return maxdepth;
}
//测试
int main(){
BiTree *t;
int x;
int depth;
printf("请以先序输入树的所有结点值:\n");
t=CreateTree(t);//初始化建树
//先序遍历
printf("先序遍历结果为:\n");
PreOrder(t);
printf("\n");
printf("中序遍历结果为:\n");
InOrder(t);
printf("\n");
printf("后续遍历结果为\n");
PostOrder(t);
printf("\n");
CountLeaf(t,&x);
printf("二叉树叶子节点数为:%d\n",x);
depth=Depth(t);
printf("二叉树的深度为:%d\n",depth);
}
实验结果