《编程之美》 3.8 求二叉树节点中的最大距离
问题:如果把二叉树看成一个图,并且父子结点之间的连线看成是双向的,姑且定义“距离”为两个结点之间边的个数,求一棵二叉树中相距最远的两个结点之间的距离。
解法一:详见《编程之美》3.8以及代码。
代码一:
typedef struct BinTreeNode
{
char data;
int nMaxLeft;
int nMaxRight;
BinTreeNode *lchild,*rchild;
};
/*------------------------------------------------------------------------*/
void FindMaxDist(BinTreeNode *pRoot)
{
if (pRoot == NULL) {
return;
}
if (pRoot->lchild == NULL) {
pRoot->nMaxLeft = 0;
}
if (pRoot->rchild == NULL) {
pRoot->nMaxRight = 0;
}
if (pRoot->lchild != NULL) {
FindMaxDist(pRoot->lchild);
}
if (pRoot->rchild != NULL) {
FindMaxDist(pRoot->rchild);
}
if (pRoot->lchild != NULL) {
int nTempMax = 0;
if (pRoot->lchild->nMaxLeft > pRoot->lchild->nMaxRight) {
nTe