二叉树中两个结点的最远距离

二叉树是我们熟悉的数据结构之一,它的面试题也有很多,今天我们就来看下二叉树中两个结点的最远距离。

分析:

第一步:

                      

第二步:

                            

在分析完之后,我们就可以写代码了

//方法一:求二叉树的左右子树的高度之和就是最远距离,但是要递归求,然后比较
typedef int T;
struct TreeNode
{
	T data;
	TreeNode* pLeft;
	TreeNode* pRight;

};
int Height(TreeNode* pRoot)
{
	if (pRoot == NULL)
		return 0;
	if (pRoot->pLeft == NULL&&pRoot->pRight == NULL)
		return 1;

	int leftHeight = Height(pRoot->pLeft);
	int RightHeight = Height(pRoot->pRight);

	return leftHeight > RightHeight ? leftHeight + 1 : RightHeight + 1;
}
void FathestDistan(TreeNode* pRoot, int &MaxValue)
{
	if (pRoot == NULL)
		return;

	int LeftHeight = Height(pRoot->pLeft);
	int RightHeight = Height(pRoot->pRight);

	if (LeftHeight + RightHeight > MaxValue)
		MaxValue = LeftHeight + RightHeight;

	if (pRoot->pLeft != NULL)
		return FathestDistan(pRoot->pLeft, MaxValue);
	if (pRoot->pRight != NULL)
		return FathestDistan(pRoot->pRight, MaxValue);
}

这种方式虽然简单直接,但是效率较差,因为在求左右子树的高度时,产生了许多的重复代码。我们进行改进如下:

//方法二,自底向上求左右子树的高度

int FathestDistan2(TreeNode* pRoot, int &MaxValue)
{
	if (pRoot == NULL)
		return 0;
	int LeftOfHeight = FathestDistan2(pRoot->pLeft, MaxValue);
	int RightOfHeight = FathestDistan2(pRoot->pRight, MaxValue);

	if (LeftOfHeight + RightOfHeight > MaxValue)
		MaxValue = LeftOfHeight + RightOfHeight;

	return LeftOfHeight > RightOfHeight ? LeftOfHeight + 1 : RightOfHeight + 1;
}

我们利用自底向上求左右子树的方式,去除了求高度的重复代码,提高了效率。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值