Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1519. Number of Nodes in the Sub-Tree With the Same Level

Rain Hu

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


一、題目

You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).
The edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.
Return an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.
A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.

Example 1:
q3e1

Example 2: q3e2

Example 3: q3e3

Constraints:


二、分析

三、解題

1. DFS

vector<int> res;
vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {
    vector<vector<int>> graph(n);       // 先將 undirected graph 轉成每個節點有哪些鄰居
    for (const auto& e : edges) {
        graph[e[0]].push_back(e[1]);
        graph[e[1]].push_back(e[0]);
    }
    res.assign(n, 0);
    dfs(graph, labels, -1, 0);          // 起點為 0,而節點不為負,過 last 可假定為任意負數
    return res;
}
vector<int> dfs(vector<vector<int>>& graph, string& labels, int last, int curr) {
    vector<int> path(26, 0);            // 用一陣列記錄字符出現的次數
    path[labels[curr]-'a']++;
    for (const auto& next : graph[curr]) {
        if (last == next) continue;     // 進到上一輪的數字則跳過
        vector<int> tmp = dfs(graph, labels, curr, next);
        add(path, tmp);                 // 將遍歷完的結果加起來
    }
    res[curr] = path[labels[curr]-'a']; // 在後序的時間點,把統計完的結果記錄下來
    return path;
}
void add(vector<int>& a, vector<int>& b) {  // 用參考的方法做陣列的加法,也不回傳,可以省下空間
    for (int i = 0; i < 26; i++) 
        a[i] += b[i];
}

回目錄 Catalog


Share this post on:

Previous
[IT] Shell 筆記
Next
[LeetCode] 100. Same Tree