parent[0] == -1 which indicates that 0 is the root.
value.length == nodes
-105 <= value[i] <= 105
The given input is guaranteed to represent a valid tree.
Solutions
Solution 1: DFS
Thinking
A subtree whose values sum to \(0\) is deleted. \(n \le 10^4\), so one bottom-up DFS: sum children's values and surviving sizes, then zero the size if this subtree sums to \(0\). The root's surviving size is the answer. Post-order deletes children before the parent decides.
First, we convert the tree into a graph \(g\), where \(g[i]\) represents all the child nodes of node \(i\).
Then we design a function \(\textit{dfs}(i)\), which represents the number of nodes and the sum of the weights in the subtree rooted at node \(i\). The answer is \(\textit{dfs}(0)[1]\).
In this function, we recursively calculate the number of nodes and the sum of the weights in the subtree rooted at each child node \(j\), and then accumulate these values. If the accumulated value is zero, we set the number of nodes in this subtree to zero. Finally, we return the number of nodes and the sum of the weights in the subtree rooted at node \(i\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the tree.
A subtree whose values sum to \(0\) is deleted. With \(n \le 10^4\), one bottom-up pass is enough: sum children's values and surviving sizes, then zero the size if this subtree sums to \(0\). Recursing into each child is too deep: a chain makes the call depth \(n\).
An explicit stack of \((\textit{node}, \textit{state})\) runs that postorder. On entry we push the exit marker and then the children; on exit we add each child's sum and surviving size, and zero the size when the sum is \(0\). The root's surviving size is the answer.
First, we convert the tree into a graph \(g\), where \(g[i]\) represents all the child nodes of node \(i\).
Then an explicit stack walks the tree in postorder. When node \(i\) is left, we add the sum and the surviving size of each child. If the accumulated sum is zero, we set this subtree's surviving size to zero. The answer is the surviving size of the root.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the number of nodes in the tree.