Skip to content

1519. Number of Nodes in the Sub-Tree With the Same Label

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
 public:
  vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
    vector<int> ans(n);
    vector<vector<int>> tree(n);

    for (const vector<int>& edge : edges) {
      const int u = edge[0];
      const int v = edge[1];
      tree[u].push_back(v);
      tree[v].push_back(u);
    }

    dfs(tree, 0, -1, labels, ans);
    return ans;
  }

 private:
  vector<int> dfs(const vector<vector<int>>& tree, int u, int prev,
                  const string& labels, vector<int>& ans) {
    // count[i] := the number of letters down from ('a' + i)
    vector<int> count(26);

    for (const int v : tree[u]) {
      if (v == prev)
        continue;
      vector<int> childCount = dfs(tree, v, u, labels, ans);
      for (int i = 0; i < 26; ++i)
        count[i] += childCount[i];
    }

    ans[u] = ++count[labels[u] - 'a'];  // the u itself
    return count;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
  public int[] countSubTrees(int n, int[][] edges, String labels) {
    int[] ans = new int[n];
    List<Integer>[] graph = new List[n];

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] edge : edges) {
      final int u = edge[0];
      final int v = edge[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    dfs(graph, 0, -1, labels, ans);
    return ans;
  }

  private int[] dfs(List<Integer>[] graph, int u, int prev, final String labels, int[] ans) {
    // count[i] := the number of letters down from ('a' + i)
    int[] count = new int[26];

    for (final int v : graph[u]) {
      if (v == prev)
        continue;
      int[] childCount = dfs(graph, v, u, labels, ans);
      for (int i = 0; i < 26; ++i)
        count[i] += childCount[i];
    }

    ans[u] = ++count[labels.charAt(u) - 'a']; // the u itself
    return count;
  }
}