编程之美3.8题,距离定为,树中两个节点之间的边数。书中的方法并不好,将左右子树的距离定义在节点中,一般的节点是已经定义好的,并无此项。</span>
经分析,理解编写代码如下:

代码如下:

struct node
{
	int data;
	node *pleft;
	node *pright;
};

struct RESULT
{
	int maxdistance;
	int maxdepth;

};


RESULT searchmaxdistance(node *root)
{
	RESULT result,lhs,rhs;
	if (root==NULL)
	{
		result.maxdepth=-1;
		result.maxdistance=0;
		return result;
	}

	lhs=searchmaxdistance(root->pleft);
	rhs=searchmaxdistance(root->pright);

	result.maxdepth=max(lhs.maxdepth+1,rhs.maxdepth+1);
	result.maxdistance=max(max(lhs.maxdistance,rhs.maxdistance),lhs.maxdepth+rhs.maxdepth+2);//为啥老是打错啊,注意细节,注意啊,注意细节啊lhs.maxdepth+rhs.maxdistance+2
	return result;
}


相关文章:

  • 2022-12-23
  • 2021-09-04
  • 2021-10-18
  • 2022-02-26
  • 2022-01-27
  • 2021-05-24
  • 2022-12-23
猜你喜欢
  • 2022-01-05
  • 2021-10-22
相关资源
相似解决方案