[LeetCode] Delete Tree Nodes

1273. Delete Tree Nodes

A tree rooted at node 0 is given as follows:

  • The number of nodes is nodes;
  • The value of the ith node is value[i];
  • The parent of the ith node is parent[i].

Remove every subtree whose sum of values of nodes is zero.

Return the number of the remaining nodes in the tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
vector<vector<int>> g;
pair<int, int> helper(int u, vector<int>& va) {
int sum = 0, child = 0;
for(auto& v : g[u]) {
auto [s, c] = helper(v, va);
sum += s;
child += c;
}

return {sum + va[u], sum + va[u] ? child + 1 : 0};
}
public:
int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {
g = vector<vector<int>>(nodes);
int root;
for(int i = 0; i < nodes; i++)
if(parent[i] != -1)
g[parent[i]].push_back(i);
else root = i;
return helper(root, value).second;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/13/PS/LeetCode/delete-tree-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.