二叉树的深度,求第k层的节点个数,二叉树的销毁,二叉树寻找值为x的节点

本文详细介绍了如何在二叉树中计算节点深度、确定k层节点数量,以及如何递归地销毁二叉树和查找特定值的节点。通过代码示例展示了这些操作的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、二叉树的深度

int BTreeHeight(BTNode* root)
{
	if (root == NULL)
		return 0;
	int rightHeight = BTreeHeight(root->right);
	int leftHeight = BTreeHeight(root->left);
	return rightHeight > leftHeight 
		? rightHeight + 1 
		: leftHeight + 1;
}
int main()
{
	BTNode* node1 = BuySTNode(1);
	BTNode* node2 = BuySTNode(2);
	BTNode* node3 = BuySTNode(3);
	BTNode* node4 = BuySTNode(4);
	BTNode* node5 = BuySTNode(5);
	BTNode* node6 = BuySTNode(6);
	BTNode* node7 = BuySTNode(7);

	node1->left = node2;
	node1->right = node4;
	node2->right = node5;
	node2->left = node3;
	node4->left = node6;
	node4->right = node7;
	printf("%d", BTreeHeight(node1));
	
	return 0;
}

在这里插入图片描述

二、二叉树的k层节点个数

int	BTreeLevelKSize(BTNode* root,int k)
{
	if (root==NULL)
		return 0;
	if (k == 1)
		return 1;
	return BTreeLevelKSize(root->left,k-1)
		+ BTreeLevelKSize(root->right, k - 1);
}

在这里插入图片描述

三、二叉树的销毁

熟悉了前面的递归,销毁递归基本上是小菜一碟,从最下面的节点开始销毁

void BTreeDistroy(BTNode* root)
{
	if (root == NULL)
		return;
	BTreeDistroy(root->left);
	BTreeDistroy(root->right);

}

四、二叉树查找值为x的节点

BTNode* BTreeFind(BTNode* root,int x)
{
	if (root == NULL)
		return NULL;
	if (root->data == x)
	return root;

	BTNode*  ret1 = BTreeFind(root->left,x);
	if (ret1->data == x)
	return ret1;
	BTNode* ret2 = BTreeFind(root->right,x);
	if (ret2->data == x)
	return ret2;
	return NULL;
}

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早睡早起^_^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值