二叉树是我们熟悉的数据结构之一,它的面试题也有很多,今天我们就来看下二叉树中两个结点的最远距离。
分析:
第一步:
第二步:
在分析完之后,我们就可以写代码了
//方法一:求二叉树的左右子树的高度之和就是最远距离,但是要递归求,然后比较
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;
}
我们利用自底向上求左右子树的方式,去除了求高度的重复代码,提高了效率。