递归计算二叉树叶子结点数递归计算二叉树叶子结点数
B12-4
题目:编写递归算法,计算二叉树中叶子结点的数目。
一、需求分析
二、概要设计
int LeafCount_BiTree(Bitree T)//求二叉树中叶子结点的数目 {
if(!T) return 0; //空树没有叶子
else if(!T->lchild&&!T->rchild) return 1; //叶子结点
else return Leaf_Count(T->lchild)+Leaf_Count(T->rchild);//左子树的叶子数加上右子树的叶子数
}/...
递归计算二叉树叶子结点数
B12-4
目:编写递归算法,计算二叉树中叶子结点的数目。
一、需求分析
二、概要设计
int LeafCount_BiTree(Bitree T)//求二叉树中叶子结点的数目 {
if(!T) return 0; //空树没有叶子
else if(!T->lchild&&!T->rchild) return 1; //叶子结点
else return Leaf_Count(T->lchild)+Leaf_Count(T->rchild);//左子树的叶子数加上右子树的叶子数
}//LeafCount_BiTree
3 详细设计
#include
#define MaxSize 100
#define MaxWidth 40
typedef char elemtype;
typedef struct node
{
elemtype data;
struct node *left,*right;
}BTree;
void dispstack(BTree*stack[],int top); void creatree(BTree * &b,char *str) {
BTree *stack[MaxSize],*p;
int top=-1,k,j=0;
char ch;
b=NULL;
ch=str[j];
while (ch!='\0')
{
switch(ch)
{
case '(': top++;stack[top]=p;k=1;break;
case ')': top--;break;
case ',': k=2;break;
default: p=(BTree *)malloc(sizeof(BTree));
p->data=ch;p->left=p=->right=NULL;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1: stack[top]->left=p;break;
case 2: stack[top]->right=p;break;
}
}
}
j++;
ch=str[j];
}
}
void printree(BTree *b) {
if(b!=NULL)
{
printf("%c",b->data);
if(b->left!=NULL||b->right!=NULL)
{
printf("%c","(");
printree(b->left);
if(b->right!=NULL) printf("%c",",");
printree(b->right);
printf("%c",")");
}
}
}
int leafs(BTree *b) {
int num1,num2;
if(b==NULL)
return 0;
else if(b->left==NULL&&b->right==NULL)
return 1;
else
{
num1=leafs(b->left);
num2=leafs(b->right);
return(num1+num2);
}
}
main()
{
BTree *b;
creatree(b,"(a(b(c),d(e(,f),g)))");
printf("b xiangqian kuohao biaoshifa:");printree(b);
printf("\n");
printf("yezhi jiedian geshu:",leafs(b),"\n");
}
三、调试分析
有一个错误没有改过来~void creatree(BTree * &b,char *str) 四、用户使用说明
五、测试结果
六、附录
本文档为【递归计算二叉树叶子结点数】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。