A tree rooted at node 0 is given as follows:
- The number of nodes is
nodes
; - The value of the
i
-th node isvalue[i]
; - The parent of the
i
-th node isparent[i]
.
Remove every subtree whose sum of values of nodes is zero.
After doing so, return the number of nodes remaining in the tree.
Example 1:
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1] Output: 2
Example 2:
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-2] Output: 6
Example 3:
Input: nodes = 5, parent = [-1,0,1,0,0], value = [-672,441,18,728,378] Output: 5
Example 4:
Input: nodes = 5, parent = [-1,0,0,1,1], value = [-686,-842,616,-739,-746] Output: 5
Constraints:
1 <= nodes <= 10^4
parent.length == nodes
0 <= parent[i] <= nodes - 1
parent[0] == -1
which indicates that0
is the root.value.length == nodes
-10^5 <= value[i] <= 10^5
- The given input is guaranteed to represent a valid tree.
class Solution:
def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int:
def dfs(u):
for v in g[u]:
dfs(v)
value[u] += value[v]
counter[u] += counter[v]
if value[u] == 0:
counter[u] = 0
g = defaultdict(list)
for i, p in enumerate(parent):
if p != -1:
g[p].append(i)
counter = [1] * nodes
dfs(0)
return counter[0]
class Solution {
private Map<Integer, List<Integer>> g;
private int[] counter;
private int[] value;
public int deleteTreeNodes(int nodes, int[] parent, int[] value) {
g = new HashMap<>();
for (int i = 0; i < nodes; ++i) {
if (parent[i] != -1) {
g.computeIfAbsent(parent[i], k -> new ArrayList<>()).add(i);
}
}
this.value = value;
counter = new int[nodes];
Arrays.fill(counter, 1);
dfs(0);
return counter[0];
}
private void dfs(int u) {
for (int v : g.getOrDefault(u, Collections.emptyList())) {
dfs(v);
value[u] += value[v];
counter[u] += counter[v];
}
if (value[u] == 0) {
counter[u] = 0;
}
}
}
class Solution {
public:
unordered_map<int, vector<int>> g;
vector<int> counter;
vector<int> value;
int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) {
for (int i = 0; i < nodes; ++i)
if (parent[i] != -1)
g[parent[i]].push_back(i);
counter.resize(nodes, 1);
this->value = value;
dfs(0);
return counter[0];
}
void dfs(int u) {
for (int v : g[u])
{
dfs(v);
value[u] += value[v];
counter[u] += counter[v];
}
if (value[u] == 0) counter[u] = 0;
}
};
func deleteTreeNodes(nodes int, parent []int, value []int) int {
g := make(map[int][]int)
for i, p := range parent {
if p != -1 {
g[p] = append(g[p], i)
}
}
counter := make([]int, nodes)
for i := range counter {
counter[i] = 1
}
var dfs func(u int)
dfs = func(u int) {
if vs, ok := g[u]; ok {
for _, v := range vs {
dfs(v)
value[u] += value[v]
counter[u] += counter[v]
}
}
if value[u] == 0 {
counter[u] = 0
}
}
dfs(0)
return counter[0]
}