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

参考:http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html

他的方法比书上的更易懂。

#include<iostream>
#include<algorithm>
using namespace std;

struct TreeNode{
	TreeNode* left;
	TreeNode* right;
};

struct RESULT{	
	int MaxDistance;//以它为根,节点的之间的最大距离
	int MaxDepth;//当前节点的最大深度
};

RESULT GetMaxDistance(TreeNode* root)
{
	if(root == nullptr)
	{
		RESULT empty{ 0, -1 };//-1是为了返回之后,加回0
		return empty;
	}
	RESULT l = GetMaxDistance(root->left);
	RESULT r = GetMaxDistance(root->right);

	RESULT result;
	result.MaxDepth = max(l.MaxDepth+1, r.MaxDepth+1);
	result.MaxDistance = max(max(l.MaxDistance, r.MaxDistance), l.MaxDepth + r.MaxDepth + 2);

	return result;
}

void Link(TreeNode* nodes, int parent, int left, int right)
{
	if(left != -1)
		nodes[parent].left = &nodes[left];

	if(right != -1)
		nodes[parent].right = &nodes[right];
}

void main()
{
	// P. 241 Graph 3-12
	TreeNode test1[9] = { 0 };
	Link(test1, 0, 1, 2);
	Link(test1, 1, 3, 4);
	Link(test1, 2, 5, 6);
	Link(test1, 3, 7, -1);
	Link(test1, 5, -1, 8);
	cout << "test1: " << GetMaxDistance(&test1[0]).MaxDistance << endl;

	// P. 242 Graph 3-13 left
	TreeNode test2[4] = { 0 };
	Link(test2, 0, 1, 2);
	Link(test2, 1, 3, -1);
	cout << "test2: " << GetMaxDistance(&test2[0]).MaxDistance << endl;

	// P. 242 Graph 3-13 right
	TreeNode test3[9] = { 0 };
	Link(test3, 0, -1, 1);
	Link(test3, 1, 2, 3);
	Link(test3, 2, 4, -1);
	Link(test3, 3, 5, 6);
	Link(test3, 4, 7, -1);
	Link(test3, 5, -1, 8);
	cout << "test3: " << GetMaxDistance(&test3[0]).MaxDistance << endl;

	// P. 242 Graph 3-14
	// Same as Graph 3-2, not test

	// P. 243 Graph 3-15
	TreeNode test4[9] = { 0 };
	Link(test4, 0, 1, 2);
	Link(test4, 1, 3, 4);
	Link(test4, 3, 5, 6);
	Link(test4, 5, 7, -1);
	Link(test4, 6, -1, 8);
	cout << "test4: " << GetMaxDistance(&test4[0]).MaxDistance << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_22080999/article/details/81390529