#include<>
#include<>
typedef char ElemType;
typedef struct BTNode
{
ElemType data;
struct BTNode *left;
struct BTNode *right;
}BTNode,*BiTree;
//创建二叉树
void createBTNode(BiTree &BT)
{
ElemType ch;
scanf("%c",&ch);
if(ch==' ')
BT=NULL;
else
{
BT = (BTNode*)malloc(sizeof(BTNode));
BT->data= ch;
createBTNode(BT->left);
createBTNode(BT->right);
}
}
//先序遍历二叉树
void printDLR(BiTree BT)
{
if(BT)
{
printf("%c ",BT->data);
printDLR(BT->left);
printDLR(BT->right);
}
}
//统计二叉树结点个数
void countLeaves(BiTree BT,int &count)
{
if(BT)
{
if(BT->left==NULL && BT->right==NULL)
count++;
else{
countLeaves(BT->left,count);
countLeaves(BT->right,count);
}
}
}
void main()
{
BTNode *BT;
int count=0;
createBTNode(BT);
printf("先序遍历:");
printDLR(BT);
printf("\n");
countLeaves(BT,count);
printf("二叉树结点的个数:%d\n",count);
}
按照先序遍历的方式来输入二叉树结点,若孩子结点为空,则输入空格。
输入:
ABD E CF
返回结果:
先序遍历:A B D E C F
二叉树结点的个数:3
叶子结点分别是:D、E、F