编写实现二叉树建立和遍历的基本算法的函数,并在此基础上设计一个主程序完成如下功能:
⑴定义二叉树的二叉链表存储结构;
⑵以扩展先序遍历序列建立二叉树的二叉链表;
⑶分别实现二叉树的先序、中序和后续遍历,并打印输出;
⑷计算二叉树的高度;
⑸计算二叉树节点的个数。
⑹计算二叉树叶子节点的个数。
# define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
int count = 0;//统计节点数
int leafcount = 0;统计叶子节点数
typedef char Elemtype;
typedef struct BitreeNode
{
Elemtype data;
struct BitreeNode* lchild, * rchild;
} BitreeNode,* Bitree;
Bitree CreatBitree(Bitree bt)
{
char ch;
scanf("%c", &ch);
if (ch == '*')
bt = NULL;
else
{
bt = (Bitree)malloc(sizeof(BitreeNode));
bt->data = ch;
bt->lchild = CreatBitree(bt);
bt->rchild = CreatBitree(bt);
}
return bt;
}
void PrintfTree(Bitree bt,int h)//按树状打印二叉树,右左中打印二叉树,节点的左右由层次决定,h表示节点的层次,每个层次相隔4个空格
{
if (bt == NULL)return;
PrintfTree(bt->rchild, h + 4);
for (int i = 0; i < h; i++)
printf(" ");
printf("%c\n", bt->data);
PrintfTree(bt->lchild, h + 4);
}
void PreOrder(Bitree bt)
{
if (bt != NULL)
{
printf("%c", bt->data);
PreOrder(bt->lchild);
PreOrder(bt->rchild);
count++;
}
}
void lnOrder(Bitree bt)
{
if (bt != NULL)
{
lnOrder(bt->lchild);
printf("%c", bt->data);
lnOrder(bt->rchild);
}
}
void PostOrder(Bitree bt)
{
if (bt != NULL)
{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
printf("%c", bt->data);
}
}
int posttreeDepth(Bitree bt)
{
int h1, hr, max;
if (bt != NULL)
{
h1 = posttreeDepth(bt->lchild);
hr = posttreeDepth(bt->rchild);
max = h1 > hr ? h1 : hr;
return (max + 1);//内部返回代码运行至此处一个递归返回值
}
else return 0;//总体返回
}
void leaf(Bitree bt)
{
if (bt != NULL)
{
leaf(bt->lchild);
leaf(bt->rchild);
if((bt->lchild == NULL) &&( bt->rchild == NULL))
leafcount++;
}
}
int main()
{
Bitree p = NULL;
p = CreatBitree(p);
PrintfTree(p, 3);
printf("先序输出:\n");
PreOrder(p);
printf("\n");
printf("中序输出:\n");
lnOrder(p);
printf("\n");
printf("后序输出:\n");
PostOrder(p);
printf("\n");
int m = posttreeDepth(p);
printf("该二叉树的高度为:%d", m);
printf("该二叉树的节点数为:%d", count);
leaf(p);
printf("该二叉树的叶子节点数为:%d", leafcount);
}