编写函数int nodeCount(BiTNode *T),统计二叉树的结点个数,编写函数int leafCount(BiTNode *T),统计二叉树的叶子个数
编写函数int oneDegree(BiTNode *T),统计二叉树的度为1的结点个数。
#include <iostream>
using namespace std;
struct BitNode
{
char data;
BitNode *lchild;
BitNode *rchild;
};
void CreatBitree(BitNode *&T)
{
char ch;
cin>>ch;
if(ch=='#') T=NULL;
else
{
T=new BitNode;
T->data=ch;
CreatBitree(T->lchild);
CreatBitree(T->rchild);
}
}
int nodecount(BitNode *T) //统计二叉树的结点个数
{
if(T==NULL) return 0;
else return nodecount(T->lchild)+nodecount(T->rchild)+1;
}
int leafcount(BitNode *T) //统计二叉树的叶子个数
{
if(T==NULL) return 0;
else
if(T->lchild==NULL&&T->rchild==NULL) return 1;
else return leafcount(T->lchild)+leafcount(T->rchild);
}
int oneDegree(BitNode *T) //统计二叉树的度为1的结点个数
{
if(T==NULL) return 0;
else
if((T->lchild!=NULL&&T->rchild==NULL)||(T->lchild==NULL&&T->rchild!=NULL)) return 1;
else return oneDegree(T->lchild)+oneDegree(T->rchild);
}
int main()
{
BitNode *T=NULL;
CreatBitree(T); //创建一颗二叉树
cout<<"二叉树的结点个数:"<<nodecount(T)<<endl; //统计二叉树的结点个数
cout<<"二叉树的叶子个数:"<<leafcount(T)<<endl; //统计二叉树的叶子个数
cout<<"二叉树的度为1的结点个数:"<<oneDegree(T)<<endl; //统计二叉树的度为1的结点个数
return 0;
}