题目来自编程之美
题目
举例(图是网上偷的,在此谢过)
上例中,最大距离为4
思路
后序遍历 + 根据结点的深度 求解 以该节点为根的距离
该节点的距离 等于 其两个子树的最大深度之和
代码
struct BTNode
{
int m_nData;
BTNode* m_pLeft;
BTNode* m_pRight;
};
int MaxDistance(BTNode* pRoot,int& nMaxDist)
{
if (!pRoot)
{
return 0;
}
int nLeftDept = MaxDistance(pRoot->m_pLeft,nMaxDist);
int nRightDept = MaxDistance(pRoot->m_pRight,nMaxDist);
nMaxDist = max(nLeftDept + nRightDept,nMaxDist);
return max(nLeftDept,nRightDept) + 1;
}
文中总结递归的思路很好。