数据结构之二叉树

编写函数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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值