You are given a tree where each node has a color (an integer). For each node, count how many distinct colors appear in its subtree. If you store colors naively, merging sets for each node can be slow. A chain tree will cause quadratic time.
Small-to-large merging makes this efficient. You will maintain a set per subtree and merge them using the technique I showed you. Let me walk through the solution step by step.