First DFS: compute subtree sizes so you can identify the heavy child. Second DFS: for node , process all children. Take the frequency map from the largest child. For each smaller child, iterate its map and merge counts into the large map.
Update count[color] for each color. After merging all children, increment count[color[v]]. Then scan the entire map to find the max frequency and sum all colors with that frequency. Store the sum as the answer for .
This runs in time and uses space.