统计二叉树中叶子结点的个数
来源:百度知道 编辑:UC知道 时间:2024/05/31 22:37:48
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))