递归计算树的深度

递归计算二叉树的深度

设计思路

  • 比较左右子树的深度 ,谁大取谁

代码展示



//计算一颗二叉树的深度,可以采用递归实现
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 @ 2025-05-14 20:42  Arroyol  阅读(36)  评论(0)    收藏  举报