Approach
Depth-first search
For Number of Nodes in the Sub Tree with the Same Label, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 79 lines of Python from the credited upstream file number-of-nodes-in-the-sub-tree-with-the-same-label.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def countSubTrees(self, n, edges, labels):6 """7 :type n: int8 :type edges: List[List[int]]9 :type labels: str10 :rtype: List[int]11 """12 def iter_dfs(labels, adj, node, parent, result):13 stk = [(1, (node, parent, [0]*26))]14 while stk:15 step, params = stk.pop()16 if step == 1:17 node, parent, ret = params18 stk.append((4, (node, ret)))19 stk.append((2, (node, parent, reversed(adj[node]), ret)))20 elif step == 2:21 node, parent, it, ret = params22 child = next(it, None)23 if not child or child == parent:24 continue25 ret2 = [0]*2626 stk.append((2, (node, parent, it, ret)))27 stk.append((3, (ret2, ret)))28 stk.append((1, (child, node, ret2)))29 elif step == 3:30 ret2, ret = params31 for k in xrange(len(ret2)):32 ret[k] += ret2[k]33 else:34 node, ret = params35 ret[ord(labels[node]) - ord('a')] += 136 result[node] += ret[ord(labels[node]) - ord('a')]37 38 adj = [[] for _ in xrange(n)]39 for u, v in edges:40 adj[u].append(v)41 adj[v].append(u)42 result = [0]*n43 iter_dfs(labels, adj, 0, -1, result)44 return result45 46 474849import collections50 51 52class Solution2(object):53 def countSubTrees(self, n, edges, labels):54 """55 :type n: int56 :type edges: List[List[int]]57 :type labels: str58 :rtype: List[int]59 """60 def dfs(labels, adj, node, parent, result):61 count = [0]*2662 for child in adj[node]:63 if child == parent:64 continue65 new_count = dfs(labels, adj, child, node, result)66 for k in xrange(len(new_count)):67 count[k] += new_count[k]68 count[ord(labels[node]) - ord('a')] += 169 result[node] = count[ord(labels[node]) - ord('a')]70 return count71 72 adj = [[] for _ in xrange(n)]73 for u, v in edges:74 adj[u].append(v)75 adj[v].append(u)76 result = [0]*n77 dfs(labels, adj, 0, -1, result)78 return result79