您的位置:首页 > 其它

微软100题(11) 二叉树中节点的最大距离

2015-05-24 16:36 330 查看
题目:

求二叉树中节点的最大距离...

如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,

我们姑且定义"距离"为两节点之间边的个数。

写一个程序,

求一棵二叉树中相距最远的两个节点之间的距离

我觉得相隔最远的 应该是左子树最深的 和 右子树最深的结点之间

所以转变为求左子树深度 和 右子树深度 最长距离为左右子树深度之和

int TreeDepth(BinaryTreeNode* pRoot)
{
	if(pRoot==NULL) return 0;
	int left = TreeDepth(pRoot->m_left);
	int right = TreeDepth(pRoot->m_right);

	return (left>right)?(left+1):(right+1);
}
但是这种想法是错误的,如果树是这样的

a

/

b

/ \

c d

/ / \

g e f

最远距离不是左右子树深度之和,而是g和f,属于b节点的左右子树之和,所以需要对每个节点进行计算,然后判断是否是最大值。

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

int nMaxLen = 0;

// 寻找树中最长的两段距离
void FindMaxLen(NODE* pRoot)
{
	// 遍历到叶子节点,返回
	if(pRoot == NULL)
		return;
	// 如果左子树为空,那么该节点的左边最长距离为0
	if(pRoot -> pLeft == NULL)
		pRoot -> nMaxLeft = 0;
	// 如果右子树为空,那么该节点的右边最长距离为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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: