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

来源:互联网 发布:macbookpro必装软件 编辑:程序博客网 时间:2024/04/30 09:00
编程之美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+2return result;}


0 0
原创粉丝点击