如果我们把二叉树看成一个图,
父子节点之间的连线看成是双向的,
我们姑且定义"距离"为两节点之间边的个数。
写一个程序,
求一棵二叉树中相距最远的两个节点之间的距离。
思路:运用递归算法即可,
void maxedge(BSTree root, int& icount, int& maxnum)
{
if (root == NULL)
return;
++icount;
maxedge(root->m_pleft, icount, maxnum);
maxedge(root->m_pright, icount, maxnum);
if (icount > maxnum)
maxnum = icount;
--icount;
}
int main()
{
......
int icount(0), maxnum(0);
maxedge(root, icount, maxnum);
std::cout << "The max path:" << maxnum - 1 << std::endl;
return 0;
}