Description
二叉树按照二叉链表方式存储,编写程序,计算二叉树中叶子结点的数目。
Input
按先序输入二叉树各节点,其中#表示取消建立子树结点。
Output
输出二叉树中叶子数目的结点
Sample Input ABD##EH###CF#I##G##
Sample Output 4
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
char data;
struct node*lchild;
struct node*rchild;
}BiTNode,*BiTree;
void creat(BiTree*root)
{
char ch;
ch=getchar();
if(ch=='#')
{
*root=NULL;
}
else{
*root=(BiTree)malloc(sizeof(BiTNode));
(*root)->data=ch;
creat(&((*root)->lchild));
creat(&((*root)->rchild));
}
}
int num(BiTree root)
{
int number;
if(root==NULL)
{
number=0;
}
else if((root->lchild==NULL)&&(root->rchild==NULL))
{
number=1;
}
else
{number=(num(root->lchild)+num(root->rchild));}
return number;
}
int main()
{
BiTree root;
creat(&root);
int n;
n=num(root);
printf("%d\n",n);
return 0;
}
本文介绍了一个简单的C语言程序,该程序通过先序遍历的方式读取二叉树结构,并计算并输出二叉树中叶子节点的数量。程序首先创建二叉树,然后递归地计算每个节点的左右子树中叶子节点的数量。
1089

被折叠的 条评论
为什么被折叠?



