您的位置:首页 > 其它

39.二叉树中任意两个节点间的最大距离

2011-08-03 12:25 302 查看
求一个二叉树中任意两个节点间的最大距离,

两个节点的距离的定义是这两个节点间边的个数,

比如某个孩子节点和父节点间的距离是1,和相邻兄弟节点间的距离是2,优化时间空间复

杂度。

思路:1.对二叉树中的任一个节点,求得它到左子树中最深的结点的距离ldis,再求得它到右子树中最深的节点的距离rdis

2.则经过此节点的任意两点的最大距离Maxdis=ldis+rdis。

3.因此,遍历二叉树中每个节点,求得经过每个节点的任意两节点间的最大距离,比较找出最大的。

代码如下:

#include<iostream>
#include<vector>

using namespace std;

struct BinaryTreeNode
{
int m_value;
BinaryTreeNode *m_pleft;
BinaryTreeNode *m_pright;
};
//int dis=0;
int Maxdis=0;
void creatBinaryTree(BinaryTreeNode * &r,int m)
{
if(r==NULL)
{
BinaryTreeNode *t=new BinaryTreeNode();
t->m_pleft=NULL;
t->m_pright=NULL;
t->m_value=m;
r=t;
}

if(m < r->m_value)
creatBinaryTree(r->m_pleft,m);
if(m > r->m_value)
creatBinaryTree(r->m_pright,m);
//if(m == r->m_value)
//	cout<<"加入重复结点!"<<endl;

}

int get_depth(BinaryTreeNode *r);
void FindMaxDis(BinaryTreeNode *r)
{
int ldis=0,rdis=0;
//vector<int> vec;
if(r==NULL)
return;
if(r->m_pleft)
{

ldis=get_depth(r->m_pleft);
//vec.pop_back();
}
if(r->m_pright)
{

rdis=get_depth(r->m_pright);
//vec.pop_back();
}

if((ldis+rdis)>Maxdis)
Maxdis=ldis+rdis;

FindMaxDis(r->m_pleft);
FindMaxDis(r->m_pright);

}

int get_depth(BinaryTreeNode *r)
{
int depth=0;
if(r)
{
int a=get_depth(r->m_pleft);
int b=get_depth(r->m_pright);
depth=(a>b)?a:b;
depth++;
}
return depth;
}

int main()
{
BinaryTreeNode *r=NULL;
creatBinaryTree(r,10);
creatBinaryTree(r,5);
creatBinaryTree(r,12);
creatBinaryTree(r,4);
creatBinaryTree(r,3);
creatBinaryTree(r,7);
creatBinaryTree(r,8);
creatBinaryTree(r,9);
creatBinaryTree(r,2);
cout<<get_depth(r)<<endl;
FindMaxDis(r);
cout<<Maxdis<<endl;

return 0;

}


get_depth是求深度,转化到求距离时要注意

书上给的这段代码更规范!

/*

* return the depth of the tree

*/

int get_depth(Tree *tree) {

int depth = 0;

if ( tree ) {

int a = get_depth(tree->left);

int b = get_depth(tree->right);

depth = ( a > b ) ? a : b;

depth++;

}

return depth;

}

/*

* return the max distance of the tree

*/

int get_max_distance(Tree *tree) {

int distance = 0;

if ( tree ) {

// get the max distance connected to the current node

distance = get_depth(tree->left) + get_depth(tree->right);

// compare the value with it's sub trees

int l_distance = get_max_distance(tree->left);

int r_distance = get_max_distance(tree->right);

distance = ( l_distance > distance ) ? l_distance : distance;

distance = ( r_distance > distance ) ? r_distance : distance;

}

return distance;

}

解释一下,get_depth 函数是求二叉树的深度,用的是递归算法:

一棵二叉树的深度就是它的左子树的深度和右子树的深度,两者的最大值加一。

get_max_distance 函数是求二叉树的最大距离,也是用递归算法:

首先算出经过根节点的最大路径的距离,其实就是左右子树的深度和;

然后分别算出左子树和右子树的最大距离,三者比较,最大值就是当前二叉树的最大距离了。

这个算法不是效率最高的,因为在计算二叉树的深度的时候存在重复计算。

但应该是可读性比较好的,同时也没有改变原有二叉树的结构和使用额外的全局变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐