MediumNo. 1519
Number of Nodes in the Sub-Tree With the Same Label — LeetCode 1519 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table, Counting
- 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0690 | Employee Importance | Medium |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
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.