数据结构:
|
以二叉链表作为二叉树的存储结构,统计二叉树的叶结点个数。首先建树,递归走起。 |
#include<iostream>
using namespace std;
int ans; //叶子节点数
typedef struct biTnode{
char data;
struct biTnode *lc,*rc;
}biTnode,*bitree;
void cr_bitree(bitree &T)
{//先序建树
char ch;
cin>>ch;
if(ch=='#') T = NULL;//空树
else{
T= new biTnode;//ch!='#',建节点
T->data = ch;
cr_bitree(T->lc);// 左子树
cr_bitree(T->rc);// 右子树
}
}
void find(bitree T)
{
if(T==NULL) return;//节点为空不计入
if(T->lc==NULL&&T->rc==NULL)
ans++;//当且仅当左右孩子为空,节点date不为空时,ans++;
else
{
find(T->lc);//找左树(左孩子)
find(T->rc);//找右树(右孩子)
}
}
int main()
{
ans=0;
bitree T;
cr_bitree(T);
find(T);
cout<<ans<<endl;
delete T;
return 0;
}
输出的结果:
本文介绍了一种使用递归方法在二叉链表结构中统计二叉树叶节点数量的C++实现。通过先序遍历的方式,首先构建二叉树,然后递归地检查每个节点,如果节点是叶节点(即没有左右子节点),则增加计数。这种方法为理解和实现二叉树的遍历提供了一个实用的例子。
1189

被折叠的 条评论
为什么被折叠?



