You are given a tree having ‘N’ nodes rooted at node 0. Each node has a label. For every node in the tree, your task is to determine the total number of nodes in the current node’s subtree, having the same label as the current node.
Note:
1. All the edges in the given tree are bidirectional.
2. The tree does not contain any cycle or self-loop.
3. A label can only be any lowercase English letter.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the ‘T’ test cases follow.
The first line of each test case contains an integer, ‘N’, denoting the total number of nodes in the tree.
The second line contains a string having ‘N’ characters, where for every, ‘i’ from 0 to ‘N-1’, the ‘i-th’ character denotes the label of the ‘i-th’ node.
Then 'N-1' lines follow. Each line contains two space-separated integers, denoting an edge between these two integers.
Output Format:
For each test case, return an array of size ‘N’, where the ‘i-th’ integer denotes the total number of nodes in the subtree of the ‘(i-1)-th’ node, having the same label as the ‘(i-1)-th’ node.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 10^4
Time Limit: 1sec
1
3
aba
0 1
0 2
2 1 1

In the first test case, there are just two nodes in the subtree of node 0 that has the same label as node 0 and that is node 0 and node 2. In the subtree of node 1, there is just one such node and it is node 1 itself. Similarly, for node 2, there is again just one such node. So we print 2 1 1.
1
4
abbb
0 1
0 2
1 3
1 2 1 1

In the second test case, there is just one node that has the same label as node 0 and that is node 0 itself. In the subtree of node 1, there are two nodes having the same label as node 1, these nodes are node 1 and node 3. For node 2, there is just one such node and it is node 2 itself. Similarly, for node 3, there is again just one such node. So we print 1 2 1 1.
Think of a DFS approach.
The approach is to use Depth First Search. We can observe that the number of nodes in the subtree of the current node having the same label as the current node is equal to the total sum of the number of such nodes in each of the current node’s children. We can add 1 to this sum as the current node is also a part of the subtree. For each node, we can maintain a list of the frequencies of each character in the subtree of that node. We can avoid repetitions by keeping a track of all the nodes that we have already VISITED.
O(N), where ‘N’ is the number of nodes in the tree.
We are visiting each node just once and calculating the frequencies using the frequencies for the child nodes so this takes constant time. Since there are ‘N’ nodes, we require O(N) time.
O(N), where 'N' is the number of nodes in the tree.
We need extra space to maintain the list of frequencies of characters for every node. Since there are ‘N’ nodes, we need O(N) extra space.