假设二叉树采用二叉链存储结构,编写一个算法,求出二叉树中的叶子结点数,并设计主函数调用上述算法。
#include<iostream>//蓝多多算法实验五:二叉树的应用(二)
#include<stdio.h>
#include<malloc.h>
using namespace std;
typedef char ElemType;
typedef struct Bnode
{
ElemType data;
struct Bnode* LChild, * RChild;
} BNode, * BTree;
void InitList(BTree &BT)//初始化
{
BT = NULL;
}
void preCreateBTree(BTree& BT)
{
char data;
data = getchar();
if (data == '#') BT = NULL;
else
{
BT = (BTree)malloc(sizeof(Bnode));
BT->data = data;
preCreateBTree(BT->LChild);
preCreateBTree(BT->RChild);
}
}
int LeafCount(BTree bt)
{
int num1, num2;
if (bt == NULL) return 0;
else if (bt->LChild == NULL && bt->RChild == NULL)
return 1;
else
{
num1 = LeafCount(bt->LChild);
num2 = LeafCount(bt->RChild);
return(num1 + num2);
}
}
int main()
{
BTree bt;
cout << "二叉树初始化中......" << endl;
InitList(bt);
cout << "请输入给定的二叉树先序序列" << endl;
preCreateBTree(bt);
cout << endl;
cout << "二叉树中的叶子结点数为" << endl;
cout << LeafCount(bt) << "个" << endl;
system("pause");
}
结果截图: