2 回答
TA贡献1798条经验 获得超7个赞
既然都能写遍历的程序,你只要设置一个全局的变量count,在遍历的时候遇到叶子节点加1就成啊,至于怎么判断叶子结点就是判断他的左右子节点是否都为NULL就可以了
TA贡献1735条经验 获得超5个赞
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))
/*当前处理的子树不为空或栈不为空则循环*/
{
while (t)
{
printf("%c",t->data);
if(t->rightchild)
{
s.top++;
s.data[s.top]=t;
}
//左右子树都为空则计数
else if(!t->leftchild){n++; printf("_");}
t=t->leftchild;
}
if (s.top>-1)
{
t=pop(&s);
t=t->rightchild;
}
}
printf("\nLeaf count=%d\n",n);
}
添加回答
举报
