Number of Nodes in the Sub-Tree With the Same Label — LeetCode 1519 Python Solution
MediumTreeDepth-First SearchBreadth-First SearchHash TableCounting
- Problem
- #1519
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.
Example
- Input
- n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"
- Output
- [2,1,1,1,1,1,1]
- Explanation
- Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.
Python solution
Python
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
def dfs(i, fa):
ans[i] -= cnt[labels[i]]
cnt[labels[i]] += 1
for j in g[i]:
if j != fa:
dfs(j, i)
ans[i] += cnt[labels[i]]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
cnt = Counter()
ans = [0] * n
dfs(0, -1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
LeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 690Employee ImportanceMediumLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1123Lowest Common Ancestor of Deepest LeavesMedium
Frequently asked questions
- How hard is LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
- LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label cover?
- LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Counting on LeetCode.