遍历过程采用先序序列。
在构造二叉树时,直接输入二叉树的先序序列,我在注释中有例子。
#include<stdio.h> #include<malloc.h> struct node{ char info; struct node *llink,*rlink; }; typedef struct node NODE; NODE *creat(){ char x; NODE *p; scanf("%c",&x); printf("%c",x); if(x!='.'){//测试输入 ABD..EH...CF.I..G.. . 表示该结点无子树 也就是返回上一层递归 p=(NODE *)malloc(sizeof(NODE)); p->info=x; p->llink=creat(); p->rlink=creat(); } else p=NULL; return p; } int Countleaf(NODE *bt,int count){//计算叶子结点 if(bt!=NULL){//根节点不为空 if(bt->llink==NULL&&bt->rlink==NULL)//左右子树都为NULL 即该结点为叶子结点,count ++ count++; count=Countleaf(bt->llink,count);// 不为空,先去遍历左子树,再次调用Countleaf函数。 count=Countleaf(bt->rlink,count); } return count; } int main(){ NODE *T; int count = 0; printf("PLease input a tree:\n"); T=creat(); printf("\n"); count = Countleaf(T,count); printf("递归算法-->二叉树的叶子结点数为:%d",count); printf("\n"); } 运行结果: PLease input a tree: ABD..EH...CF.I..G.. ABD..EH...CF.I..G.. 递归算法—>二叉树的叶子结点数为:4 -------------------------------- Process exited after 15.37 seconds with return value 0