编程之美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;
}