Description
二叉树按照二叉链表方式存储,编写程序,计算二叉树中叶子结点的数目。
Input
按先序输入二叉树各结点,其中#表示取消建立子树结点。
Output
输出二叉树中叶子节点的数目。
- Sample Input
ABD##EH###CF#I##G##
- Sample Output
4
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
typedef struct BinTreeNode
{
char data;
struct BinTreeNode *lchild;
struct BinTreeNode *rchild;
}BinTree, *PBinTree;
PBinTree CreateBinTree()
{
PBinTree root = (PBinTree)malloc(sizeof(BinTree));
char c = getchar();
if(c == '#')
return NULL;
else
{
root->data = c;
root->lchild = CreateBinTree();
root->rchild = CreateBinTree();
}
return root;
}
int LeafNum(PBinTree root)
{
if(!root)
return 0;//这一步总是忘
else
{
if((!root->lchild)&&(!root->lchild))
return 1;
else
return LeafNum(root->lchild)+LeafNum(root->rchild);
}
}
int main()
{
PBinTree T;
T = CreateBinTree();
printf("%d\n",LeafNum(T));
return 0;
}
叶子节点就是结度为0的点