求二叉树叶子数与高度(C++)

我们首先来看一看二叉树中叶子数与高度的定义:

叶子数:对于一个二叉树的节点,若其既没有左子树又没有右子树,那它就是叶子节点。整个二叉树的叶子数为所有叶子节点个数。

高度:二叉树高度又称深度,其为根节点到叶子节点路径的最大值。

下面提供实现代码:

#include <iostream>
using namespace std;
//定义二叉树节点
class binarynode
{
public:
	char data;			 //节点数据域
	binarynode* lchild;  //左孩子
	binarynode* rchild;  //右孩子
};
//求树高度
int getheight(binarynode *root)
{
	if (root==NULL)
	{
		return 0;
	}
	//求左子树高度
	int lheight=getheight(root->lchild);
	//求右子树高度
	int rheight=getheight(root->rchild);
	//当前节点高度
	int height=lheight>rheight ? lheight+1 : rheight+1;;
	return height;
}
//求叶子节点
void calculateleafnum(binarynode* root,int* leafnum)
{
	if (root==NULL)
	{
		return;
	}
	if (root->rchild==NULL && root->lchild==NULL)
	{
		(*leafnum)++;
	}
	//左子树节点数目
	calculateleafnum(root->lchild,leafnum);
	//右子树节点数目
	calculateleafnum(root->rchild,leafnum);
}
//创建二叉树
void createtree()
{
	//创建节点
	binarynode node1={'A',NULL,NULL};
	binarynode node2={'B',NULL,NULL};
	binarynode node3={'C',NULL,NULL};
	binarynode node4={'D',NULL,NULL};
	binarynode node5={'E',NULL,NULL};
	binarynode node6={'F',NULL,NULL};
	binarynode node7={'G',NULL,NULL};
	binarynode node8={'H',NULL,NULL};
	//建立节点关系
	node1.lchild=&node2;
	node1.rchild=&node6;
	node2.rchild=&node3;
	node3.lchild=&node4;
	node3.rchild=&node5;
	node6.rchild=&node7;
	node7.lchild=&node8;
	//计算二叉树高度
	int height=getheight(&node1);
	cout<<"二叉树的高度为:"<<height<<endl;
	//计算二叉树叶子数
	int num=0;
	calculateleafnum(&node1,&num);
	cout<<"二叉树的节点为:"<<num<<endl;
}

int main()
{
	createtree();
	system("pause");
	return 0;

 

 

 

 

 

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值