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

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

2013-08-22 21:16 471 查看


推荐

http://blog.csdn.net/zsuguangh/article/details/6367914
http://blog.csdn.net/houhouzhe/article/details/6549348 http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html


问题定义

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

#include <iostream>
using namespace std;
struct Tree{
int data;
Tree* left;
Tree* right;
int leftmax;//左子树中最长距离
int rightmax;//右子树中最长距离
};
//max{d(u1,v1),...d(uk,vk),max1+max2+2}
void build(Tree *&root){
Tree *t1 = new Tree();
t1->data = 1;
Tree *t2 = new Tree();
t2->data = 2;
Tree *t3 = new Tree();
t3->data = 3;
Tree *t4 = new Tree();
t4->data = 4;
Tree *t5 = new Tree();
t5->data = 5;
Tree *t6 = new Tree();
t6->data = 6;
Tree *t7 = new Tree();
t7->data = 7;
Tree *t8 = new Tree();
t8->data = 8;
Tree *t9 = new Tree();
t9->data = 9;
t1->left = t2;
t1->right = t3;
t2->left = t4;
t2->right = t5;
t4->left = t6;
t4->right = t7;
t6->left = t8;
t6->right = NULL;
t7->left = NULL;
t7->right = t9;
t3->left = NULL;
t3->right = NULL;
t5->left = NULL;
t5->right = NULL;
t8->left = NULL;
t8->right = NULL;
t9->left = NULL;
t9->right = NULL;
root = t1;
}
void prints(Tree *root){
if(root==NULL)return;
if(root->left)prints(root->left);
if(root->right)prints(root->right);
cout<<root->data<<"  ";
}
int max(int a,int b){
return a>b?a:b;
}
int maxlen = 0;
void calc(Tree* root){
if(root==NULL)return ;
if(root->left==NULL)
root->leftmax = 0;
if(root->right==NULL)
root->rightmax = 0;
if(root->left)
calc(root->left);
if(root->right)
calc(root->right);
//计算左子树最长距离
if(root->left){
int tempmax = root->left->leftmax>root->left->rightmax?root->left->leftmax:root->left->rightmax;
root->leftmax = tempmax+1;
}
//计算右子树最长距离
if(root->right){
int tempmax = root->right->leftmax>root->right->rightmax?root->right->leftmax:root->right->rightmax;
root->rightmax = tempmax+1;
}
//更新最长距离
if(root->leftmax+root->rightmax>maxlen){
maxlen = root->leftmax+root->rightmax;
}
}
int main(){
Tree *root;
build(root);
//prints(root);
calc(root);
cout<<maxlen<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程之美