1519. Number of Nodes in the Sub-Tree With the Same Label
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
def dfs(node):
if node in visited:
return Counter()
label_counter = Counter()
visited.add(node)
label_counter[labels[node]] += 1
for child in graph[node]:
label_counter += dfs(child)
answer[node] = label_counter[labels[node]]
return label_counter
graph = defaultdict(list)
answer = [0 for _ in range(n)]
visited = set()
for x, y in edges:
graph[x].append(y)
graph[y].append(x)
dfs(0)
return answer