统计二叉树中叶子结点的个数

来源:百度知道 编辑:UC知道 时间:2024/05/31 22:37:48
1. 在文件test.cpp中已经给出的创建一个二叉树的算法的基础上,分别设计递归和非递归的算法统计该二叉树中叶子结点的个数。
test.cpp 的内容如下:
#include <stdio.h>
#include <malloc.h>
typedef char datatype; /*结点属性值的类型*/
typedef struct node{ /*二叉树结点的类型*/
datatype data;
struct node *leftchild, *rightchild;
}BiTreeNode;

#define Max 100
typedef struct
{
BiTreeNode* data[Max];
int top;
}seqstack;

FILE *rf ;

void Initiate(BiTreeNode **root) //二叉树的初始化
{
*root=(BiTreeNode*)malloc(sizeof(BiTreeNode));
(*root)->leftchild=NULL;
(*root)->rightchild=NULL;
}

void Destroy(BiTreeNode **root) //释放二叉树
{
if((*root)!=NULL &&(*root)->leftchild!=NULL)
Destroy(&(*root)->leftchild);
if((*root)!=NULL &&(*root)->rightchild!=NULL)
Destroy(&(*root)->rightchild);
free(*root);
}

void createbintree(BiTreeNode **t) //创建二叉树
{
char ch;

既然都能写遍历的程序,你只要设置一个全局的变量count,在遍历的时候遇到叶子节点加1就成啊,至于怎么判断叶子结点就是判断他的左右子节点是否都为NULL就可以了

int Nochild(BiTree T)
{
int num1,num2,n=0;
if(T==NULL)
return(0)
else
if(T->lchild==NULL&&T->rchild=NULL)
n=1;
num1= Nochild(T->lchild);
num2= Nochild(T->rchild);
return(num1+num2+n);
}
这个是求叶子结点个数的函数

int LeafCountResc(BiTreeNode *tree)
{ //递归实现二叉树的遍历统计叶子数
BiTreeNode *t = tree;
int total = 0;

if(!t) return 0;

//如果已经是叶子,则返回1
//作为调试,打印叶子值
if(!t->leftchild && !t->rightchild )
{printf("%c ", t->data); return 1;}

//否则分别统计左子树和右子树的叶子数量

total += LeafCount(t->leftchild);
total += LeafCount(t->rightchild);
return total;
}

void LeafCountLoop(BiTreeNode *t)
/*非递归实现二叉树的前序遍历, 统计叶子数*/
{
int n = 0;
seqstack s;
s.top=-1;
while ((t) || (s.top!=-1))

求二叉树中叶子结点的数目 关于数据结构里的算法问题!问题是:写出统计二叉树中叶子结点数的算法.有哪位会尽快解答,要详细答案! 求,编写递归算法,统计二叉树中度为2的结点个数(C语言) 一棵树共有n个结点的树,其中所有分支结点的度为k,则该树中叶子结点的个数为? 完全二叉树的结点个数为11,则它的叶结点个数为??? 以二叉链为存储结构,写一算法求二叉树的叶子结点个数 二叉树结点的计算?? 采用二叉链表存储结构,按前根序输入二叉树的结点序列,建立二叉树并中根序遍历该二叉树,计算叶子节点的个数 在深度为5的满二叉树中,叶子结点的个数为多少? 求查找二叉树子叶(结点)个数的C程序