思路1:
直接遍历这棵二叉树,求叶子结点数
代码1:
int n=0;
int count(BTNode *t){
//int n=0;
if(t){
if(t->lchild==NULL&&t->rchild==NULL)
++n;
count(t->lchild);
count(t->rchild);
}
return n;
}
思路2:
先求左子树叶子结点数,再求右子树叶子结点数,返回二者之和
代码2:
int count2(BTNode *t){
int n1,n2;
if(t==NULL)
return 0;
else if(t->lchild==NULL&&t->rchild==NULL)
return 1;
else
{
n1=count2(t->lchild);
n2=count2(t->rchild);
return n1+n2;
}
}
测试:
#include<stdio.h>
#include <stdlib.h>
#include<math.h> //数学函数,求平方根、三角函数、对数函数、指数函数...
//用于使用c++的输出语句
#include<iostream>
using namespace std;
typedef struct BTNode
{
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
void createBiTree(BTNode* &T);
void preOrder(BTNode *t);
int count(BTNode *t);
int count2(BTNode *t);
void visit(BTNode *p);
//二叉树用二叉链表存储,设计一个算法,可以求出一颗二叉树的叶子结点数
void main(){
BTNode *t;
createBiTree(t);
preOrder(t);
cout<<count(t)<<endl;
cout<<count2(t)<<endl;
}
//直接遍历这棵二叉树,求叶子结点数
int n=0;
int count(BTNode *t){
//int n=0;
if(t){
if(t->lchild==NULL&&t->rchild==NULL)
++n;
count(t->lchild);
count(t->rchild);
}
return n;
}
//先求左子树叶子结点数,再求右子树叶子结点数,返回二者之和
int count2(BTNode *t){
int n1,n2;
if(t==NULL)
return 0;
else if(t->lchild==NULL&&t->rchild==NULL)
return 1;
else
{
n1=count2(t->lchild);
n2=count2(t->rchild);
return n1+n2;
}
}
void createBiTree(BTNode* &T)
{
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else
{
T=(BTNode *)malloc(sizeof(BTNode));
T->data=ch;
cout<<"put in \'"<<T->data<<"\' lchild"<<endl;
createBiTree(T->lchild);
cout<<"put in \'"<<T->data<<"\' rchild"<<endl;
createBiTree(T->rchild);
}
}
void preOrder(BTNode *t){
if(!t)
return;
visit(t);
preOrder(t->lchild);
preOrder(t->rchild);
}
void visit(BTNode *p){
cout<<p->data<<"\t";
//...
}
本文介绍两种方法来计算二叉树的叶子节点数。第一种方法是直接遍历二叉树,第二种方法是分别计算左右子树的叶子节点数并相加。附带相关代码实现和测试。
4055

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



