编写递归算法 计算二叉树中叶子节点的个数

 

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

 

}

    原文作者:递归算法
    原文地址: https://blog.csdn.net/jane617_min/article/details/7037440
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞