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

时间:2021-11-22 22:38:03

 

#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();

}