//【数据结构】NOJ016 计算二叉树叶子节点数目
#include <stdio.h>
#include <stdlib.h>
//二叉链表
typedef char ElemType;
typedef struct TNode
{
ElemType info;
struct TNode *lchild;
struct TNode *rchild;
}TNode,*BinTree;
void Create(BinTree *T); //创建一个二叉树
int Count(BinTree T); //先序遍历二叉树
void Create(BinTree *T) //先序输入二叉树结点
{
char ch=getchar(); //此时ch=字母或'#'
if(ch=='#')return;
(*T)=(BinTree)malloc(sizeof(TNode));
(*T)->info=ch;
(*T)->lchild=NULL;
(*T)->rchild=NULL;
Create(&((*T)->lchild));
Create(&((*T)->rchild));
}
int Count(BinTree T)
{
int cnt=0;
if(T){
if(!T->lchild&&!T->rchild)return 1; //叶子节点返回1
cnt+=Count(T->lchild); //左子树的叶子节点数
cnt+=Count(T->rchild); //右子树的叶子节点数
return cnt; //返回当前树的叶子结点数
}
else return 0; //空树返回0
}
int main()
{
BinTree T=NULL;
Create(&T);
printf("%d",Count(T));
return 0;
}
【后记】
1.第一次写递归这么顺(没有抄),居然一次AC我好感动qaq