分别设计三个方法,计算二叉树 度为1的结点个数,度为2的结点的个数,以及树的结点个数。
要求:1.构建如下二叉树:
A
/ \
B C
/ \ /
D E F
/* 二叉树的结点结构 */
#include <stdio.h>
#include <malloc.h>
typedef char ElemType; /* 数据域值类型 */
typedef struct Node {
ElemType data; /* 数据域 */
struct Node *lchild, *rchild; /* 左、右指针域,分别存储左、右孩子的存储位置 */
} BinaryTree;
/*1. 先序建立二叉树 */
BinaryTree *CreBiTree( ) {
BinaryTree *bt;
ElemType x;
scanf("%c", &x); /* 读入数据 */
if (x == '^') bt = NULL; /* 输入^,安排空指针 */
else {
bt = (BinaryTree *)malloc(sizeof(BinaryTree));
bt->data = x; /* 生成新结点 */
bt->lchild = CreBiTree(); /* 建立左子树 */
bt->rchild = CreBiTree(); /* 建立右子树 */
}
return bt; /* 返回根结点的指针 */
}
/* 先序遍历二叉树的递归算法 */
void PreOrder(BinaryTree *bt) {
if (bt != NULL) {
printf("%c", bt->data); /* 访问根结点 */
PreOrder(bt->lchild); /* 先序遍历根结点的左子树 */
PreOrder(bt->rchild); /* 先序遍历根结点的右子树 */
}
}
/* 中序遍历二叉树的递归算法 */
void InOrder(BinaryTree *bt) {
if (bt != NULL) {
InOrder(bt->lchild); /* 中序遍历根结点的左子树 */
printf("%c", bt->data); /* 访问根结点 */
InOrder(bt->rchild); /* 中序遍历根结点的右子树 */
}
}
/* 后序遍历二叉树的递归算法 */
void PostOrder(BinaryTree *bt) {
if (bt != NULL) {
PostOrder(bt->lchild); /* 后序遍历根结点的左子树 */
PostOrder(bt->rchild); /* 后序遍历根结点的右子树 */
printf("%c", bt->data); /* 访问根结点 */
}
}
int LeafCount(BinaryTree *bt) {
static int count = 0;
if (bt != NULL) {
if (bt->lchild == NULL && bt->rchild == NULL)
count++;
else {
LeafCount(bt->lchild);
LeafCount(bt->rchild);
}
}
return count;
}
int LeafCountt(BinaryTree *bt) {
if (bt == NULL)
return 0;
if (bt->lchild == NULL && bt->rchild == NULL)
return 1;
return LeafCountt(bt->lchild) + LeafCountt(bt->rchild);
}
//度为1
int LeafCount_1(BinaryTree *bt) {
if (bt == NULL)
return 0;
else if ((bt->lchild == NULL && bt->rchild != NULL) || (bt->lchild != NULL && bt->rchild == NULL))
return LeafCount_1(bt->lchild) + LeafCount_1(bt->rchild) + 1;
else
return LeafCount_1(bt->lchild) + LeafCount_1(bt->rchild);
}
//度为2
int LeafCount_2(BinaryTree *bt) {
if (bt == NULL)
return 0;
else if (bt->lchild != NULL && bt->rchild != NULL)
return LeafCount_2(bt->lchild) + LeafCount_2(bt->rchild) + 1;
return LeafCount_2(bt->lchild) + LeafCount_2(bt->rchild);
}
//结点总数
int LeafCount_All(BinaryTree *bt) {
if (bt == NULL)
return 0;
else
return LeafCount_All(bt->lchild) + LeafCount_All(bt->rchild) + 1;
}
int main() {
BinaryTree *bt;
printf("input data:");
bt = CreBiTree(); /* 可以图5.13为例建立二叉链表 ABD^^E^^CF^^^ */
printf("PreOrder result:");
PreOrder(bt);
printf("\n");
//
// printf("InOrder result:");
// InOrder(bt);
// printf("\n");
//
// printf("PostOrder result:");
// PostOrder(bt);
// printf("\n");
// printf("叶子节点的个数为:%d\n",LeafCountt(bt));
printf("度为1结点的个数为:%d\n", LeafCount_1(bt));
printf("度为2结点的个数为:%d\n", LeafCount_2(bt));
printf("结点总个数为:%d\n", LeafCount_All(bt));
}