问题定义
如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。
计算一个二叉树的最大距离有两个情况:
- 情况A: 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
- 情况B: 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
只需要计算这两个情况的路径距离,并取其大者,就是该二叉树的最大距离。
由上图可知本题的实质就在于求解 A,B并返回最大值。我用的是一种递归方法,先递归求出此次之前左右子树的高度,left,right,现在的高度:left+1,right+1;选出两者之间的最大值max1,A情况的值:left+right+2;B情况: 选出左右子树的最大深度 然后求出AB中的最大值max2(即最大深度),即是二叉树中节点的最大距离。
代码:
#include<iostream>
using namespace std;
struct NODE
{
NODE *pLeft;
NODE *pRight;
};
struct RESULT
{
int nMaxDistance;
int nMaxDepth;
};
RESULT GetMaximumDistance(NODE* root)
{
if (!root)
{
RESULT empty = { 0, -1 }; // trick: nMaxDepth is -1 and then caller will plus 1 to balance it as zero.
return empty;
}
RESULT lhs = GetMaximumDistance(root->pLeft);
RESULT rhs = GetMaximumDistance(root->pRight);
RESULT result;
result.nMaxDepth = max(lhs.nMaxDepth + 1, rhs.nMaxDepth + 1);
result.nMaxDistance = max(max(lhs.nMaxDistance, rhs.nMaxDistance), lhs.nMaxDepth + rhs.nMaxDepth + 2);
return result;
}