您的位置:首页 > 职场人生

求一个二叉树中两个结点的最大距离

2017-05-19 17:30 381 查看
首先说一下距离这个词,在二叉树中距离就是从一个节点到另一个结点的边的条数,为了更为清晰的描述这个概念,下面来看一张图:



看上面的图,蓝色线表示的是结点4到6的距离,红色线表示的是从结点5到6的距离,从图中我们可以看到,不是所有的距离都经过根结点的,这一点很重要。

那么怎么求最远距离呢?

上面的那个图中,我们可以很容易看出最远的距离就是从4到6,或者是从4到5,都是一样的。而且我们还发现,他们分别是左子树的最底层的结点和右子树最底层的结点。那么我们可不可以这样算呢,分别求出左子树和右子树的高度,然后让他们相加再加上1(根结点)。

这是最远的吗?

显然不是,下面我们再来看一个例子:



如果按照上面我们算的,最远路径应该是从2到9,也就是红色线,但是我们发现,从8到9更长。那么这里又有什么规律呢?

我们在自习看一下这个图,我们发现不管是哪一条,他们都分别在一个结点的左右子树中,所以,我们可以将所有的结点的左右子树的高度和计算一下,然后取出最大值,就是最远的距离。

接下来看一下这个问题的实现过程:

#include<iostream>
using namespace std;

#include<string>

// 孩子表示法
template<class T>
struct BinaryTreeNode
{
BinaryTreeNode(const T& value)
: _value(value)
, _pLeft(NULL)
, _pRight(NULL)
{}

T _value;
BinaryTreeNode<T>* _pLeft;   // 左孩子
BinaryTreeNode<T>* _pRight;  // 右孩子
};

template<class T>
class BinaryTree1
{
typedef BinaryTreeNode<T> Node;
public:
BinaryTree1()
:_pRoot(NULL)
{}

BinaryTree1(const T array[], size_t size, const T& invalid)
{
size_t index = 0;
_CreateBinaryTree(_pRoot, array, size, index, invalid);
}

//求一个二叉树中两个结点的最大距离
void MaxDistance()
{
int _maxlenth = 0;

//左右子树中最大深度的和
cout << _MaxDistance(_pRoot, _maxlenth) << endl;

cout << _maxlenth << endl;
}
protected:
//创建二叉树
void _CreateBinaryTree(Node* &pRoot, const T array[], size_t size, size_t& index, const T& invalid)
{
if (index < size&&array[index] != invalid)
{
pRoot = new Node(invalid);//注意new的时候要和结构体中写的函数参数对应
pRoot->_value = array[index];

_CreateBinaryTree(pRoot->_pLeft, array, size, ++index, invalid);//注意:++index
_CreateBinaryTree(pRoot->_pRight, array, size, ++index, invalid);
}
}

size_t _MaxDistance(Node* pRoot, int &maxlenth)
{
if (pRoot == NULL)
return 0;

//左右子树的长度
int leftlenth = _MaxDistance(pRoot->_pLeft, maxlenth);
int rightlenth = _MaxDistance(pRoot->_pRight, maxlenth);

//用一个临时变量保存当前的最远距离,如果大于原来的,那么交换
int temp = leftlenth + rightlenth;
if (temp > maxlenth)
maxlenth = temp;

return leftlenth > rightlenth ? leftlenth + 1 : rightlenth + 1;
}
private:
Node* _pRoot;
};

void FunTest()
{
char array[] = "12##3468####5#7#9";
//char array[] = "124###35##6";
BinaryTree1<char> bt(array, strlen(array), '#');

bt.MaxDistance();
}

int main()
{
FunTest();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐