## 页首HTML代码 ```html

树的递归遍历

数据结构

树--递归遍历

image

/****************************************************************************
 *
 * function name     :BinaryTree_CountNode
 * function          : 计算一颗二叉树的所有节点的数量,可以采用递归实现
 * parameter         :
 *                    @root
 *                  
 * Return results    : 返回成功或者失败。
 * note              : None
 * author            : tongyaqi1110@163.com
 * date              : 2024-04-30
 * version           : V1.0
 * revision history  : None
 *
 ****************************************************************************/
#include<stdio.h>
//计算一颗二叉树的所有节点的数量,可以采用递归实现
int BinaryTree_CountNode(Tnode_t *root)
{
	int n1,n2; //n1用于记录左子树的节点,n2用于记录右子树的节点

	//递归函数先提前写好终止条件
	if (NULL == root)
	{
		return 0;
	}

	//假设采用后序遍历来计算二叉树的节点数量
	n1 = BinaryTree_CountNode(root->lchild);
	n2 = BinaryTree_CountNode(root->rchild);

	return n1+n2+1;
	
}

image

/****************************************************************************
 *
 * function name     : BinaryTree_CountLeafNode
 * function          : 计算一颗二叉树的所有叶子节点的数量,可以采用递归实现
 * parameter         :
 *                    @root
 *                  
 * Return results    : 返回成功或者失败。
 * note              : None
 * author            : tongyaqi1110@163.com
 * date              : 2024-04-30
 * version           : V1.0
 * revision history  : None
 *
 ****************************************************************************/

#include<stdio.h>
//计算一颗二叉树的所有叶子节点的数量,可以采用递归实现
int BinaryTree_CountLeafNode(Tnode_t *root)
{
	int n1,n2; //n1记录左子树叶子节点,n2记录右子树叶子结点

	//1.递归函数必须提前写好终止条件
	if (NULL == root)
	{
		//说明是空树,则直接返回0
		return 0;
	}
	else if(root->lchild == NULL && root->rchild == NULL)
	{
		//说明只有一个根节点,则根节点就是叶子节点
		return 1;
	}
	else
	{
		//说明是有子树的二叉树,则需要计算左子树的叶子节点和右子树的叶子节点
		n1 = BinaryTree_CountLeafNode(root->lchild);
		n2 = BinaryTree_CountLeafNode(root->rchild);
	}

	return n1+n2;
}

image

/****************************************************************************
 *
 * function name     : BinaryTree_CountLeafNode
 * function          : 计算一颗二叉树的所有叶子节点的数量,可以采用递归实现
 * parameter         :
 *                    @root
 *                  
 * Return results    : 返回成功或者失败。
 * note              : None
 * author            : tongyaqi1110@163.com
 * date              : 2024-04-30
 * version           : V1.0
 * revision history  : None
 *
 ****************************************************************************/

//计算一颗二叉树的深度,可以采用递归实现
int BinaryTree_GetDepth(Tnode_t *root)
{
	int n1,n2;//n1记录左子树的深度,n2记录右子树的深度

	//1.递归函数必须提前写好终止条件
	if (NULL == root)
	{
		//说明是空树,则返回0
		return 0;
	}
	else
	{
		//说明是子树的二叉树,则分别计算左子树和右子树,取最大
		n1 = BinaryTree_GetDepth(root->lchild);
		n2 = BinaryTree_GetDepth(root->rchild);
	}

	return ( (n1>n2)?n1:n2) + 1;
}

posted @ 2024-05-01 00:21  一面小镜子  阅读(37)  评论(0)    收藏  举报