C语言——数据结构二叉树笔试题

假设二叉树采用二叉链存储结构,设计一个算法,计算一棵给定二叉树的所有叶子结点数

/**
 * @name       BinaryTree_CountLeafNode
 * @brief      计算一棵给定二叉树的所有叶子结点数
 * @param      root 根节点 
 * @return	   leftCount + rightCount 叶子结点数
 *     @retval   
 * @date       2025/05/08
 * @version    1.0
 * @note       
 */
int BinaryTree_CountLeafNode(BinaryTree_t *root)
{
	// 递归函数终止条件
	if ( root == NULL )
	{
		// 空树
		return 0;
	}else if ( root->lchild == NULL && root->rchild ==NUll )
	{
		// 只有一个根结点
		return 1;
	}else
	{
		int leftCount  = BinaryTree_CountLeafNode(root->lchild); // 左子树的叶子结点数
		int rightCount = BinaryTree_CountLeafNode(root->rchild); // 右子树的叶子结点数

	}
	return leftCount + rightCount;
}

假设二叉树采用二叉链存储结构,设计一个算法,计算一棵给定二叉树的所有结点数

image-20250509222146281

/**
 * @name       BinaryTree_CountNode
 * @brief      假设二叉树采用二叉链存储结构,设计一个算法,计算一棵给定二叉树的所有叶子结点数
 * @param      root 根结点
 * @return
 *     @retval leftCount + rightCount +1 结点数   
 * @date       2025/05/08
 * @version    1.0
 * @note       
 */
int BinaryTree_CountNode(BinaryTree_t *root)
{
	// 递归函数终止条件
	if ( root == NULL )
	{
		return 0;
	}
	int leftCount  = BinaryTree_CountNode(root->lchild); // 左子树的叶子结点数
	int rightCount = BinaryTree_CountNode(root->rchild); // 右子树的叶子结点数

	return leftCount + rightCount + 1;
}

写一个算法求一棵二叉树的深度二叉树以二叉链表为存储方式。

image-20250509224825621

/**
 * @name       BinaryTree_GetDepth
 * @brief      求一棵二叉树的深度二叉树以二叉链表为存储方式
 * @param      root 根节点 
 * @return	   (leftCount > rightCount ? leftCount : rightCount) + 1 深度
 *     @retval   
 * @date       2025/05/08
 * @version    1.0
 * @note       
 */
int BinaryTree_GetDepth(BinaryTree_t *root)
{
	// 递归函数终止条件
	if ( root == NULL )
	{
		// 空树
		return 0;
	}else
	{
		int leftCount  = BinaryTree_CountLeafNode(root->lchild); // 左子树深度
		int rightCount = BinaryTree_CountLeafNode(root->rchild); // 右子树深度

	}
	return (leftCount > rightCount ? leftCount : rightCount) + 1;
}
posted @ 2025-05-14 20:12  九思0404  阅读(16)  评论(0)    收藏  举报