题目要求:以二叉链表作存储结构,建立一棵二叉树。 输出该二叉树的先序、中序、后序遍历序列,求出该二叉树的深度,并统计其叶子结点数。
二叉链表的类型描述:
typedef char ElemType;
typedef struct BiNode
{
ElemType data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
输入格式:
输入一个二叉树的先序序列,孩子为空的位置以#替代。
输出格式:
输出分五行
第一行 先序遍历序列
第二行 中序遍历序列
第三行 后序遍历序列
第四行 二叉树深度
第五行 叶子结点数
其中遍历过程中按访问顺序打印出结点的内容时,字符间均无间隔。
具体格式参看输出样例。
对于下图中给出的二叉树:
输入样例:
ABD##FE###CG#H##I##
输出样例:
PreOrder:ABDFECGHI
InOrder:DBEFAGHCI
PostOrder:DEFBHGICA
Depth:4
Leaf:4
代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiNode {
ElemType data;
struct BiNode* lchild;
struct BiNode* rchild;
} BiNode, * BiTree;
// 根据先序序列构建二叉树
BiTree createBiTree() {
char ch;
scanf("%c", &ch);
if (ch == '#') {
return NULL;
}
BiNode* node = (BiNode*)malloc(sizeof(BiNode));
node->data = ch;
node->lchild = createBiTree();
node->rchild = createBiTree();
return node;
}
// 先序遍历
void preOrder(BiTree root) {
if (root != NULL) {
printf("%c", root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
}
// 中序遍历
void inOrder(BiTree root) {
if (root != NULL) {
inOrder(root->lchild);
printf("%c", root->data);
inOrder(root->rchild);
}
}
// 后序遍历
void postOrder(BiTree root) {
if (root != NULL) {
postOrder(root->lchild);
postOrder(root->rchild);
printf("%c", root->data);
}
}
// 计算二叉树深度
int treeDepth(BiTree root) {
if (root == NULL) {
return 0;
}
else {
int leftDepth = treeDepth(root->lchild);
int rightDepth = treeDepth(root->rchild);
return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
}
}
// 统计叶子结点数
int countLeaves(BiTree root) {
if (root == NULL) {
return 0;
}
else if (root->lchild == NULL && root->rchild == NULL) {
return 1;
}
else {
return countLeaves(root->lchild) + countLeaves(root->rchild);
}
}
int main() {
BiTree root = createBiTree();
// 输出先序、中序、后序遍历序列
printf("PreOrder:");
preOrder(root);
printf("\n");
printf("InOrder:");
inOrder(root);
printf("\n");
printf("PostOrder:");
postOrder(root);
printf("\n");
// 输出二叉树深度
printf("Depth:%d\n", treeDepth(root));
// 输出叶子结点数
printf("Leaf:%d\n", countLeaves(root));;
return 0;
}