求二叉树中节点的最大距离

《编程之美》第3.8节:求二叉树中的最大距离

问题:如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们定义距离为两个节点之间的边数,求一棵二叉树中县局最远的两个节点之间的距离。

解法:树的后序遍历,然后再每个节点中维护两个变量nMaxLeft,nMaxRight保存当前节点为根节点的子树中的最远距离,不断更新maxLength,直到根节点。

代码:

#include<iostream>
using namespace std;

struct Node
{
	Node *left;
	Node *right;
	int nMaxLeft;
	int nMaxRight;
	char value;
	Node(char v,Node *l=nullptr,Node *r=nullptr,int nl=0,int nr=0):value(v),left(l),right(r),nMaxLeft(nl),nMaxRight(nr){}
};

void findMaxLength(Node *root,int &maxLength)
{
	if(root->left==nullptr)
		root->nMaxLeft=0;
	else
	{
		findMaxLength(root->left,maxLength);
		root->nMaxLeft=max(root->left->nMaxLeft,root->left->nMaxRight)+1;
	}
	if(root->right==nullptr)
		root->nMaxRight=0;
	else
	{
		findMaxLength(root->right,maxLength);
		root->nMaxRight=max(root->right->nMaxLeft,root->right->nMaxRight)+1;
	}
	if(maxLength<root->nMaxLeft+root->nMaxRight)
		maxLength=root->nMaxLeft+root->nMaxRight;
}

int main()
{
	Node *root=new Node('A');
	root->left=new Node('B');
	root->left->left=new Node('C');
	root->left->right=new Node('D');
	root->left->left->left=new Node('E');
	root->left->right->left=new Node('J');
	root->right=new Node('F');
/*	root->right->left=new Node('G');
	root->right->right=new Node('H');
	root->right->left->right=new Node('I');*/

	int result=0;
	findMaxLength(root,result);
	cout<<result<<endl;

	system("pause");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值