Let's root the tree at node 1.
We define the following DP arrays:
\text{downDepth}_x: the maximum depth from x to a leaf in its subtree.
\text{downDiam}_x: the diameter (in number of nodes) of the subtree rooted at x.
We compute them as:
\text{downDepth}_x = 1 + \max_{y \in \text{children}(x)} \text{downDepth}_y
\text{downDiam}_x =
\max\left(
\max_{y \in \text{children}(x)} \text{downDiam}_y,\;
1 + \text{largest two values of } \text{downDepth}_y
\right)
Now define the upward DP:
\text{upDepth}_x: the maximum depth starting from x going outside its subtree.
\text{upDiam}_x: the diameter of the tree after removing the subtree of x.
To compute \text{upDepth}_x (where p = \text{parent}(x)):
\text{upDepth}_x =
1 + \max\left(
\text{upDepth}_p,\;
\max_{y \in \text{children}(p),\, y \neq x} \text{downDepth}_y
\right)
To compute \text{upDiam}_x, we take the maximum of:
\text{upDiam}_p
\max_{y \in \text{children}(p),\, y \neq x} \text{downDiam}_y
1 + \text{largest two values among }
\left\{
\text{upDepth}_p
\right\}
\cup
\left\{
\text{downDepth}_y : y \in \text{children}(p),\, y \neq x
\right\}
Finally, for a node v, after removing it, each component corresponds to:
For each component, we compute its diameter and count centers:
\text{centers}(d) =
\begin{cases}
1 & \text{if } d \text{ is odd} \\
2 & \text{if } d \text{ is even}
\end{cases}
Thus,
\text{ans}_v =
\sum_{\text{children } u \text{ of } v} \text{centers}(\text{downDiam}_u)
\;+\;
\text{centers}(\text{upDiam}_v)
Time complexity: O(n)