求二叉树中距离最远的两个叶子节点的距离

问题:

给定一棵二叉树(非二叉检索树),求二叉树中距离最远的两个叶子节点间的距离?其中两个叶子间的距离定义为: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_
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值