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
- 34 lines of Java from the credited upstream file 1519.java.
- The implementation visibly relies on sequence storage.
- 3 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.
1class Solution {2 public int[] countSubTrees(int n, int[][] edges, String labels) {3 int[] ans = new int[n];4 List<Integer>[] graph = new List[n];5 Arrays.setAll(graph, i -> new ArrayList<>());6 7 for (int[] edge : edges) {8 final int u = edge[0];9 final int v = edge[1];10 graph[u].add(v);11 graph[v].add(u);12 }13 14 dfs(graph, 0, -1, labels, ans);15 return ans;16 }17 18 private int[] dfs(List<Integer>[] graph, int u, int prev, final String labels, int[] ans) {19 20 int[] count = new int[26];21 22 for (final int v : graph[u]) {23 if (v == prev)24 continue;25 int[] childCount = dfs(graph, v, u, labels, ans);26 for (int i = 0; i < 26; ++i)27 count[i] += childCount[i];28 }29 30 ans[u] = ++count[labels.charAt(u) - 'a']; 31 return count;32 }33}34