First pass: compute subtree sizes using a simple DFS. Store size[v] for every node. Second pass: for each node , process all children recursively. Identify the child with the largest subtree. Take that child's color set as the base.
Merge all other children's sets into it by inserting their elements. Add 's own color to the set. Count distinct colors using . Store this count as the answer for . Repeat for all nodes.
This runs in time and uses space.