Every value computed here is measured inside a subtree, so best(v) knows nothing about the tree above v. A question that wants a number at every node, such as the total distance from each node to all the others, looks like n separate runs, which is O(n squared). The fix is a second downward pass that hands each child the answer for everything outside its own subtree, which the parent can build from its own answer once that child's subtree is discounted. That is rerooting, and it keeps the cost at O(n).