Delete Tree Nodes
Description
null
Solution(javascript)
/**
* @param {number} nodes
* @param {number[]} parent
* @param {number[]} value
* @return {number}
*/
var deleteTreeNodes = function(nodes, parent, value) {
const map = {}
let size = value.length
parent.forEach((parentNode, node) => {
map[parentNode] = map[parentNode] || []
map[parentNode].push(node)
})
const aux = (node) => {
const children = map[node] || []
let currentCount = 0
let currentSum = 0;
[currentCount, currentSum] = children.reduce(([count, sum], child) => {
const [childCount, childSum] = aux(child)
return [count+childCount, sum + childSum]
}, [1, value[node]])
if(currentSum === 0) {
size -= currentCount
return [0,0]
}
return [currentCount, currentSum]
}
aux(0)
return size
};