[LeetCode] 1519. Number of Nodes in the Sub-Tree With the Same Label

김민우·2023년 1월 12일
0

알고리즘

목록 보기
113/189

- Problem

1519. Number of Nodes in the Sub-Tree With the Same Label


- 내 풀이 (dfs)

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

- 결과

profile
Pay it forward.

0개의 댓글