编写递归算法,计算二叉树中叶子结点的数目

来源:互联网 发布:芒果tv网络电视直播 编辑:程序博客网 时间:2024/04/20 08:00

 

#include<stdio.h>

struct BiTree{

    char data;

    struct BiTree *lchild;

    struct BiTree *rchild;

};

struct BiTree* CreatBiTree(){

    char x;

    struct BiTree* p;

    scanf("%c",&x); 

    if(x!='.'){

      p=(struct BiTree*)malloc(sizeof(struct BiTree));

      p->data=x;

      p->lchild=CreatBiTree();

      p->rchild=CreatBiTree();

}

    else

      p=NULL;

      return p;

}

int LeafNum(struct BiTree *T){

    if(!T)

      return 0;

    else

      if(!T->lchild&&!T->rchild)

        return 1;

      else

        return LeafNum(T->lchild)+LeafNum(T->rchild);

}

int main(){

   int num;

   struct BiTree* T;

   printf("Please input the tree(pre):\n");

   T=CreatBiTree();

   while(T==NULL){

     printf("empoty,again:\n");

       T=CreatBiTree();                                 

       }

   num=LeafNum(T);

   printf("\nthe sum of leaf is:%d\n",num);

   getch();

}