What you seem to be looking for is a diameter of / 2. You can calculate the diameter of the tree as shown below and call it findDiameter(n, null) for an arbitrary node n tree.
public findDiameter(node n, node from) returns <depth, diameter> // apply recursively on all children foreach child in (neighbors(n) minus from) do <de, di> = findDiameter(child, n) // depth of this node is 1 more than max depth of children depth = 1 + max(de) // max diameter either uses this node, then it is 1 + the 2 largest depths // or it does not use this node, then it the max depth of the neighbors diameter = max(max(di), 1 + max(de) + oneButLargest(de))
All you have to do is loop over the neighbors, tracking the largest diameter and two greatest depths.
source share