问题:
给定一棵二叉树(非二叉检索树),求二叉树中距离最远的两个叶子节点间的距离?其中两个叶子间的距离定义为:F(X,Y) = 从节点X到根节点路径上所有节点数据之和 + 从节点Y到根节点路径上所有节点数据之和 - 从X和Y的第一个祖先节点到根节点路径上所有节点数据之和。
思路:
1,后序遍历每一节点,找出该节点到最右边的距离以及最左边的距离;
2,找到之和最大的即可。
struct TNode
{
int data;
TNode * left_child;
TNode * right_child;
}
void FindMax( TNode *pNode, int &max_distance, int &tot_distance )
{
if( pNode == NULL )
{ max_distance = 0;
tot_distance = 0;
return;
}
else
{
int left_max_distance;
int left_tot_distance;
int right_max_distance;
int right_tot_distance;
FindMax( pNode->left_child, left_max_distance, left_tot_distance);
FindMax( pNode->right_child, right_max_distance, right_tot_distance);
tot_distance = left_max_distance + right_max_distance + pNode->data;
max_distance = left_max_