Python 1519.py
class Solution:
def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:
result = [ 0 ] * n
# build tree
next = defaultdict(list)
for a, b in edges:
next[a].append(b)
next[b].append(a)
# already visited
seen = set()
def deeper(node):
# don't visit twice
nonlocal seen, result
if node in seen:
return None
seen.add(node)
have = defaultdict(int)
for children in next[node]:
add = deeper(children)
if add:
for a in add:
have[a] += add[a]
# node's label
current = labels[node]
have[current] += 1
result[node] = have[current]
return have
deeper(0)
return result
Difficulty
and has an acceptance rate of about 56% (100k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Counting
- Depth First Search
- Hash Table
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method countSubTrees. The method receives the number of nodes n, an edge list describing an undirected tree, and a string labels where each character denotes the label of the corresponding node. The goal is to compute, for every node, how many nodes in its subtree (including itself) share the same label as the node. The algorithm builds an adjacency representation, performs a depth-first traversal from the root (node 0), aggregates label frequencies in a dictionary, and stores the required counts in the result list.
Building the adjacency structure
next = defaultdict(list)
for a, b in edges:
next[a].append(b)
next[b].append(a)
The code creates a defaultdict of lists named next. For each undirected edge [a, b], both directions are recorded, allowing constant-time access to a node’s neighbors during traversal. This representation is compact and avoids the need for separate parent-child bookkeeping.
Tracking visited nodes
seen = set()
A set called seen records nodes that have already been visited. Because the tree is undirected, the adjacency list contains back-edges to the parent. The seen set prevents the recursive function from revisiting a node, thereby guaranteeing termination and correctly handling the inherent bidirectional connections.
Recursive depth-first aggregation
def deeper(node):
nonlocal seen, result
if node in seen:
return None
seen.add(node)
have = defaultdict(int)
for children in next[node]:
add = deeper(children)
if add:
for a in add:
have[a] += add[a]
current = labels[node]
have[current] += 1
result[node] = have[current]
return have
The inner function deeper performs a post-order traversal. It first checks the seen set to avoid reprocessing a node. A fresh defaultdict(int) called have is created to accumulate label frequencies for the current subtree. For each neighbor (children) of the current node, the function recursively obtains the neighbor’s frequency map (add). If a map is returned, its entries are merged into have. The merging loop adds each label count from the child’s map to the parent’s map, ensuring that the parent’s map reflects the entire subtree processed so far.
After processing all children, the node’s own label (current) is incremented in have. The count for the node’s label is then stored in result[node]. Finally, the complete frequency map for the subtree rooted at node is returned to the caller.
Initiating the traversal
deeper(0)
return result
The traversal starts from node 0, which is treated as the root of the tree. Because the tree is connected, this single call reaches every node. The final result list, now populated with the required counts, is returned to the caller.
Edge-case handling
The algorithm gracefully handles several edge conditions:
-
Single-node tree: When
nequals 1, the adjacency list contains no edges. Thedeeperfunction is called on node 0,havereceives the node’s label, andresult[0]becomes 1, correctly reflecting that the sole node’s subtree contains exactly one occurrence of its label. -
Repeated labels: The frequency dictionary
haveaggregates counts for any label that appears multiple times in a subtree. The merging loop adds counts from each child, so nodes with many identical labels receive the correct total. -
Disconnected input (theoretically): Although the problem guarantees a tree, the
seenset ensures that even if the input contained extra components, the recursion would stop after exhausting reachable nodes from the root, preventing infinite loops. -
Empty label string: If
labelswere an empty string (which would be inconsistent withn), the code would attempt to indexlabels[node]and raise an exception. However, within the problem constraints,labelsalways has lengthn, so the implementation safely accesses each character.
Performance optimizations
The implementation incorporates several choices that reduce overhead:
-
Use of
defaultdictfor adjacency and frequency maps eliminates the need for explicit existence checks before appending neighbors or incrementing counts. This yields concise code and avoids conditional branches inside tight loops. -
Early exit on visited nodes (
if node in seen: return None) prevents unnecessary recursion into already processed branches. Because each node is added toseenexactly once, the total number of recursive calls equals the number of nodes, guaranteeing linear work. -
Returning
Nonefor already visited nodes allows the caller to skip the merging loop entirely for those cases, avoiding the cost of iterating over an empty dictionary. -
In-place accumulation: The
havedictionary for a node is built directly from its children’s dictionaries without creating intermediate copies. The merging loop updates the parent’s dictionary in place, minimizing memory allocations. -
Single pass traversal: By performing a post-order depth-first search, the algorithm computes the required counts in one traversal. No separate passes are needed to propagate label frequencies upward, which keeps the runtime proportional to the size of the tree.
Overall, the code delivers the desired result with a straightforward depth-first strategy, leveraging Python’s dynamic containers to keep the implementation compact while maintaining efficient execution for typical tree sizes.
ELI5 - Simplified Explanation
Imagine you have a big family tree made of colorful wooden blocks. Every block has a letter painted on it. You have a bunch of sticks connecting these blocks together so they branch out like a real tree. The goal is to look at each block and count how many blocks in the entire branch below it share the same color letter as that block.
First, a group of empty buckets is set up to keep track of the counts for every single block in the tree. Then, the connection sticks are organized so that every block knows which other blocks are attached to it.
The computer starts at the very top block and goes down along the branches. It keeps a secret list of blocks it has already looked at so it does not get confused and visit the same place twice. As it travels down to the very end of a branch, it starts counting the letters it finds on the way back up.
When the computer is at a specific block, it asks all the blocks below it, what letters do you have? It gathers all those answers together and adds its own letter to the pile. Once it knows how many letters match its own, it writes that number down in the bucket for that specific block. This happens over and over, moving from the tiny ends of the branches all the way back to the main starting block at the top, until every block has its final answer written down.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| shreymehul | C# | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| shreymehul | C# | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1726: Tuple with Same Product
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality