---
# System prepended metadata

title: 1519. Number of Nodes in the Sub-Tree With the Same Label
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

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

###### Link : https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/

## 題目
計算每個節點的子樹有幾個跟父節點一樣字母的節點。

## 程式碼

```cpp=
class Solution {
public:
    void Solve(int node, int parent, vector<vector<int>> &count, vector<vector<int>> &adj, string &labels){
        for(auto& child : adj[node]){
            if(child == parent)//不往回走
                continue;
            Solve(child, node, count, adj, labels);
            for(int i=0;i<count[child].size();i++){
                count[node][i]+=count[child][i];//將所有子節點的字母數加總
            }
        }
        count[node][labels[node]-'a']++;//加上自己的字母數
        return;
    }
    vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
        vector<vector<int>> adj(n);
        for(auto &edge : edges){//adj list
            adj[edge[0]].push_back(edge[1]);
            adj[edge[1]].push_back(edge[0]);
        }
        vector<vector<int>> count(n, vector<int>(26, 0));//計算子節點的字母數
        Solve(0, -1, count, adj, labels);

        vector<int> ans;
        for(int i=0;i<n;i++){
            ans.push_back(count[i][labels[i]-'a']);
        }
        return ans;
    }
};
```