二叉树结点的最大距离

/* 二叉树结点中的最大距离*/

struct Node
{
	Node* pLeft;            //左子树
	Node* pRight;         //右子树
	int  nMaxLeft;        //左子树中的最长距离
	int  nMaxRight;     //右子树中的最长距离
	char chValue;        //该节点的值
};

int nMaxLen = 0;

//寻找树中最长的两段距离
void FindMaxLen(Node* pRoot)
{
	//遍历叶子节点,返回;对于左右子树,如果为空
	//则返回最长距离为0,否则递归寻找两边的最长距离
	if(pRoot == NULL)
	{
		return;
	}
	if(pRoot -> pLeft == NULL)
	{
		pRoot ->nMaxLeft = 0;
	}
	if(pRoot -> pRight == NULL)
	{
		pRoot ->nMaxRight = 0;
	}
	if(pRoot -> pLeft != NULL)
	{
		FindMaxLen(pRoot -> pLeft);
	}
	if(pRoot -> pRight != NULL)
	{
		FindMaxLen(pRoot -> pRight);
	}

	//计算左子树最长节点距离
	if(pRoot -> pLeft != NULL)
	{
		int nTempMax= 0;
		if(pRoot -> pLeft ->nMaxLeft > pRoot -> pLeft -> nMaxRight)
		{
			nTempMax = pRoot -> pLeft ->nMaxLeft;
		}
		else
		{
			nTempMax = pRoot -> pLeft -> nMaxRight;
		}
		pRoot -> nMaxLeft = nTempMax +1;
	}
	//计算右子树节点最长距离
	if(pRoot -> pRight != NULL)
	{
		int nTempMax= 0;
		if(pRoot -> pRight ->nMaxLeft > pRoot -> pRight -> nMaxRight)
		{
			nTempMax = pRoot -> pRight ->nMaxLeft;
		}
		else
		{
			nTempMax = pRoot -> pRight -> nMaxRight;
		}
		pRoot -> nMaxRight = nTempMax +1;
	}

	//更新最长距离
	if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen)
	{
		nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值