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

推荐
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值