Root the tree at an arbitrary node (e.g., node 0).
Perform a post-order traversal to compute count and stsum for each node.
Initialize ans[root] with stsum[root].
Perform a pre-order traversal where for each parent-child pair (parent, child), compute ans[child] using the formula ans[child] = ans[parent] - count[child] + (n - count[child]).
Return the ans array containing the sum of distances for each node.