[C语言]二叉树计算-求叶子结点数目,树的高度

利用递归求下图的叶子结点数量以及树的深度

在这里插入图片描述

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>


//二叉树结点
typedef struct BINARYNODE {
	char ch;
	struct BINARYNODE* lchild;
	struct BINARYNODE* rchild;
}BinaryNode;



//递归求叶子数量
void CalculateLeafNum(BinaryNode* root,int *LeafNum) {
	if (root == NULL) {
		return;
	}
	if (root->lchild == NULL && root->rchild == NULL) {
		(*LeafNum)++;
	}
	//判断左子树
	CalculateLeafNum(root->lchild,LeafNum);
	//判断右子树
	CalculateLeafNum(root->rchild,LeafNum);
}


//递归求树的高度
int CalculateTreeDepth(BinaryNode* root) {
	if (root == NULL) {
		return 0;
	}
	//深度初始化为0
	int depth = 0;
	//分别求左右子树的深度
	int LeftDepth = CalculateTreeDepth(root->lchild);
	int RightDepth = CalculateTreeDepth(root->rchild);
	//取二者中最大值,并加1(本层高度)
	depth = LeftDepth > RightDepth ? LeftDepth + 1: RightDepth + 1;
	return depth;
}


//创建二叉树
void CreateBinaryTree() {
	//创建结点
	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 LeafNum = 0;
	//调用函数求叶子结点数目
	CalculateLeafNum(&node1,&LeafNum);
	printf("LeafNum = %d\n", LeafNum);
	//计算树的深度
	int Depth = CalculateTreeDepth(&node1);
	printf("TreeDepth = %d\n", Depth);
}

int main() {
	CreateBinaryTree();
	return 0;
}

运算结果

LeafNum = 3
TreeDepth = 4
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值