
Function generate(node):
arr.Add(node.id)
visited[node.id] = True
for childNode in node.children:
if childNode is not visited:
generate(childNode)
arr.Add(node.id)
You are given N = 4, ‘arr’ = [1, 2, 2, 1].The resulting graph will be

For node 1, the subtree count is 2, while for node 2 the subtree count is 1. Hence the answer is [2, 1].
The first line of input contains an integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the size of the array.
The second line of input contains ‘N’ space-separated integers representing the given array.
For each test case, print space-separated integers, representing the number of nodes in each subtree.
Print a separate line for each test case.
1 <= T <= 10
2 <= N <= 10^6
0 <= arr[i] <= 10^9
Time Limit: 1 sec
You do not need to print anything. It has already been taken care of. Just implement the function.
In this approach, we make a few observations,
We can build the tree by pushing the node id in a stack and adding the next node as the children of the top of the stack. Whenever the top of the stack is equal to the current node id in the array, then we will pop the node from the stack
After building the tree we can use DFS to find the nodes in each subtree of the tree
We will create a class TreeNode(id, children), where id is the id of the node and children is the array of child nodes of the current node.
We will create a function getSubTree(root, count), here root is the current node and count the array of subtree counts of the tree.
Algorithm:
In this approach, it can be seen that all the node IDs, between two occurrences of the same node ID in the array, are the subtree nodes of the array, and all nodes are also occurring twice. Hence the number of nodes in subtree of a node ID is half of the distance between the two occurrences of the Node ID
Algorithm:
Return count array