即二叉树中相距最远的两个节点之间的距离。
递归解法:
(1)如果二叉树为空,返回0,同时记录左子树和右子树的深度,都为0
(2)如果二叉树不为空,最大距离要么是左子树的最大距离,要么是右子树的最大距离,要么是左子树节点中到根节点的最大距离+右子树节点中到根节点的最大距离,同时记录左子树和右子树节点中到根节点的最大距离。
int GetMaxDistance(BinaryTreeNode *pRoot, int &maxLeft, int &maxRight)
{
if (pRoot == NULL) {
maxLeft = 0;
maxRight = 0;
return 0;
}
int maxLL, maxLR, maxRL, maxRR;
int maxDistLeft, maxDistRight;
if (pRoot->lchild != NULL) {
maxDistLeft = GetMaxDistance(pRoot->lchild, maxLL, maxLR);
maxLeft = max(maxLL, maxLR) + 1;
}
else {
maxDistLeft = 0;
maxLeft = 0;
}
if (pRoot->rchild != NULL) {
maxDistRight = GetMaxDistance(pRoot->rchild, maxRL, maxRR);
maxRight = max(maxRL, maxRR) + 1;
}
else {
maxDistRight = 0;
maxRight = 0;
}
return max(max(maxDistLeft, maxDistRight), maxLeft + maxRight);
}