您的位置:首页 > 编程语言

编程之美之求二叉树中节点的最大距离

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



分析:树上分析的很清楚,计算一个二叉树的最大距离有两个情况:
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=0,maxLength=0;
	findMaxLength(root,depth,maxLength);
	return maxLength;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: