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

如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。

请写一个程序,求一棵二叉树中相距最远的两个节点之间的距离。

int maxTreeDistance(TNode* root, int &maxDistance) {
	if (!root) {
		maxDistance = 0;
		return 0;
	}
	int maxLeft = 0, maxRight = 0;
	if (root->left) {
		maxLeft = maxTreeDistance(root->left, maxDistance) + 1;
	} else {
		maxLeft = 0;
	}
	if (root->right) {
		maxRight = maxTreeDistance(root->right, maxDistance) + 1;
	} else {
		maxRight = 0;
	}

	if (maxLeft + maxRight > maxDistance) {
		maxDistance = maxLeft + maxRight;
	}
	return maxLeft > maxRight ? maxLeft : maxRight;
}


你可能感兴趣的:(算法-树)