#1519
Number of Nodes in the Sub-Tree With the Same Label
MediumHash TableTreeDepth-First SearchBreadth-First SearchCountingDepth-First Search (DFS)Tree TraversalCounting with Arrays
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single DFS traversal to count labels in the subtree while returning counts up the tree. This avoids redundant calculations and efficiently aggregates results.
⚙️
Algorithm
4 steps- 1Step 1: Build the graph from the edges.
- 2Step 2: Perform a DFS starting from the root node.
- 3Step 3: Maintain a count array for labels in the subtree.
- 4Step 4: For each node, update the result based on the counts of its label.
solution.py22 lines
1def countSubtrees(n, edges, labels):
2 from collections import defaultdict
3 graph = defaultdict(list)
4 for a, b in edges:
5 graph[a].append(b)
6 graph[b].append(a)
7
8 result = [0] * n
9 def dfs(node, parent):
10 count = [0] * 26
11 count[ord(labels[node]) - ord('a')] += 1
12 for neighbor in graph[node]:
13 if neighbor != parent:
14 child_count = dfs(neighbor, node)
15 for i in range(26):
16 count[i] += child_count[i]
17 result[node] = count[ord(labels[node]) - ord('a')]
18 return count
19
20 dfs(0, -1)
21 return result
22ℹ
Complexity note: The complexity is O(n) because we perform a single DFS traversal of the tree, visiting each node once, and using additional space for the count of labels.
- 1Using DFS allows us to efficiently count nodes in subtrees without redundant calculations.
- 2Maintaining a count array for labels helps aggregate results as we backtrack through the tree.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.