计算二叉树的任意两节点的最远距离。

利用计算二叉树高度的方法计算两个节点最远距离。

计算出一个节点的深度,左右子树的深度,然后加起来,就是这个节点的最远的距离了。然后遍历二叉树的所以的节点,找出最大的节点即可。

#include <iostream>
using namespace std;
typedef struct BtreeNode
{
	int data;
	struct BtreeNode *left,*right;
}node;
void create(node *&r ,int m)
{
	if(r==NULL)
	{
		node *t = new node();
		t->data = m;
		t->left =NULL;
		t->right = NULL;
		r = t;
	}
	else
	{
		if(m<r->data)
		{
			create(r->left ,m);
		}
		else
		{
			create(r->right ,m);
		}
	}
}
int getdepth(node *r)
{
	if(r==NULL)
	{
		return 0;
	}
	else
	{
		int max = getdepth(r->left);
		if(getdepth(r->right)>max)
		{
			max = getdepth(r->right);
		}
		return (max+1);
	}
}
int maxlen=0;
void Find(node *r)
{
	int ldis ,rdis ;
	if(r==NULL)
	{
		return;
	}
	if(r->left )
	{
       ldis = getdepth(r->left);
	}
	if(r->right)
	{
		rdis = getdepth(r->right);
	}
	if(ldis+rdis>maxlen)
	{
		maxlen = ldis +rdis;
	}
	Find(r->left);
	Find(r->right);
}

void main()
{
	node *root=NULL;
	create(root,10);
	create(root,6);
	create(root,4);
	create(root,8);
	create(root,15);
	create(root,14);
	create(root,13);
	
	create(root,12);
	create(root,11);
	create(root,16);
	create(root,18);
	create(root,19);
	create(root,20);
	create(root,21);
    cout<<"深度:"<<getdepth(root)<<endl;
	Find(root);
	cout<<"最大距离"<<maxlen<<endl;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值