统计二叉树的叶结点个数。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
typedef char ElemType;
#define ERROR 0
#define OK 1
typedef struct BiNode
{
ElemType data;
BiNode* lchild, * rchild;
}BiNode,*BiTree;
bool Create_tree(BiTree& T)
{
ElemType x = 0;
scanf("%c", &x);
if (x == '#')
{
T = NULL;
}
else
{
T = (BiTree)malloc(sizeof(BiNode));
if (T == NULL)
{
cout << "内存无法分配!!!" << endl;
return ERROR;
}
T->data = x;
T->lchild = NULL;
T->rchild = NULL;
Create_tree(T->lchild);
Create_tree(T->rchild);
}
return OK;
}
void PreOrder(BiTree T)
{
if (T != NULL)
{
cout << T->data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BiTree T)
{
if (T != NULL)
{
InOrder(T->lchild);
cout << T->data;
InOrder(T->rchild);
}
}
void PostOrder(BiTree T)
{
if (T != NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout << T->data;
}
}
int leave_node_count(BiTree T)
{
if (T == NULL)
{
return 0;
}
else if (T->lchild == NULL && T->rchild == NULL)
{
return 1;
}
else
{
return leave_node_count(T->lchild) + leave_node_count(T->rchild);
}
}
//ABC##D##E##
//统计二叉树的叶结点个数
int main(void)
{
BiTree T = NULL;
Create_tree(T);
PreOrder(T);
cout << endl;
InOrder(T);
cout << endl;
PostOrder(T);
cout << endl;
cout << "二叉树的叶结点个数:" << leave_node_count(T) << endl;
return 0;
}