这是对二叉树一的补充
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
#define MaxWidth 40
int LeafCount=0;
int Layer=1;
typedef char ElemType;
typedef struct tnode
{
ElemType data;
struct tnode *lchild,*rchild;
} BTNode;
void CreateBTree(BTNode * &bt) /*创建二叉链bt*/
{
BTNode * p=NULL;
char ch;
bt=NULL;
ch=getchar(); /*先序输入序列AB.DF..G..C.E.H..*/
if (ch==‘.‘)
bt=NULL;
else
{
bt=(BTNode *)malloc(sizeof(BTNode));
bt->data=ch;
CreateBTree( bt->lchild);
CreateBTree( bt->rchild);
}
}
void PreDispBTree(BTNode *bt) /*先序输出二叉树*/
{
if (bt!=NULL)
{
printf("%c ",bt->data);
PreDispBTree(bt->lchild);
/*递归处理左子树*/
PreDispBTree(bt->rchild);
/*递归处理右子树*/
}
}
void zhongxuTree(BTNode *bt)/*编写中序输出二叉树函数*/
{
if(bt!=NULL)
{
zhongxuTree(bt->lchild);
printf("%c ",bt->data);
zhongxuTree(bt->rchild);
}
}
void houxuTree(BTNode *bt) /*编写后序输出二叉树函数*/
{
if(bt!=NULL)
{
houxuTree(bt->lchild);
houxuTree(bt->rchild);
printf("%c ",bt->data);
}
}
void yeziTree(BTNode *bt)/*编写二叉树输出叶子节点的函数*/
{
if(bt!=NULL)
{
if(bt->lchild==NULL&&bt->rchild==NULL)
{
printf("%c ",bt->data);
}
yeziTree(bt->lchild);
yeziTree(bt->rchild);
}
}
int leaf(BTNode *bt)/*统计叶子数*/
{
if(bt!=NULL)
{
leaf(bt->lchild);
leaf(bt->rchild);
if(bt->lchild==NULL&&bt->rchild==NULL)
LeafCount++;
}
return LeafCount;
}
int shenduTree(BTNode *bt)/*计算并输出二叉树的深度。*/
{
int hl,hr,max;
if(bt!=NULL)
{
hl=shenduTree(bt->lchild);
hr=shenduTree(bt->rchild);
max=hl>hr? hl:hr;
return (max+1);
}
else
return 0;
}
void PrintTree(BTNode *bt,int Layer)/*编写竖向显示二叉树(即按层显示)函数*/
{
if(bt==NULL)
return ;
PrintTree(bt->lchild,Layer+1);
for(int i=0;i<Layer;i++)
printf(" ");
printf("%c\n",bt->data);
PrintTree(bt->rchild,Layer+1);
}
void main()
{
BTNode *bt;
CreateBTree(bt);
/*构造图6.12(a)所示的二叉树*/
printf("二叉树先序序列bt:\n");
PreDispBTree(bt);
printf("\n");
printf("二叉树中序序列bt:\n");/*中序输出二叉树*/
zhongxuTree(bt);
printf("\n");
printf("二叉树后序序列bt:\n");/*后序输出二叉树*/
houxuTree(bt);
printf("\n");
printf("计算并输出二叉树的深度\n");
printf("%d\n", shenduTree(bt));
printf("输出二叉树bt叶子结点:\n");/*输出二叉树叶子结点*/
yeziTree(bt);
printf("\n");
printf("输出二叉树bt叶子结点个数:\n");/*输出二叉树叶子结点个数*/
printf("%d\n",leaf(bt));
printf("树状打印二叉树:\n");
PrintTree(bt,Layer);
printf("\n");
}