题目:如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。

1、 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。
2、 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。
但是树上的代码使用了额外的节点字段,这里给出我的代码,思路是一样的:
struct BinaryTree
{
int value;
BinaryTree* left;
BinaryTree* right;
BinaryTree(int x):value(x),left(NULL),right(NULL){}
};
void findMaxLength(BinaryTree* root,int& depth,int& maxLength)
{
if(root == NULL)
{
depth = -1;
maxLength = 0;
return;
}
int ldepth,rdepth,lmaxLength,rmaxLength;
findMaxLength(root -> left,ldepth,lmaxLength);
findMaxLength(root -> right,rdepth,rmaxLength);
depth = max(ldepth,rdepth)+1;
maxLength = max(lmaxLength,rmaxLength);
maxLength = max(maxLength,ldepth+rdepth+2);
}
int findMaxLength(BinaryTree* root)
{
int depth,maxLength;
findMaxLength(root,depth,maxLength);
return maxLength;
}编程之美之求二叉树中节点的最大距离,布布扣,bubuko.com
原文地址:http://blog.csdn.net/fangjian1204/article/details/38705153