且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

寻找一棵树的直径

更新时间:2021-08-08 18:24:09

您要返回最长路径上的节点数.因此,您算法中的问题是这一行:

You want to return the number of nodes on the longest path. Therefore, the problem in your algorithm is this line:

return max(lheight + rheight + 1,max(ldiameter,rdiameter));

其中

rootDiameter = lheight + rheight + 1

是从左侧树的最深节点到右侧树的最深节点的路径长度.但是,此计算是不正确的.单个节点返回的高度为0,因此不会被计算在内.您有两种选择:

is the length of the path from the deepest node of the left tree to the deepest node of the right tree. However, this calculation is not correct. A single node returns a height of 0, so it will not be counted. You have two options:

  1. 更改 hieghtoftree 以返回最深路径上的节点数,而不是跳数"
  2. 总结您的问题
  1. Change hieghtoftree to return the number of nodes on the deepest path and not the number of "hops"
  2. Address this problem in your summation

.

return max(lheight + rheight + 3,max(ldiameter,rdiameter));