- Difficulty: Medium
- Tags: LeetCode, Medium, Tree, Depth-First Search, Breadth-First Search, Array, leetcode-1273, O(n), DFS, DP
Problem
A tree rooted at node 0 is given as follows:
- The number of nodes is
nodes; - The value of the
ithnode isvalue[i]; - The parent of the
ithnode isparent[i].
Remove every subtree whose sum of values of nodes is zero.
Return the number of the remaining nodes 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
Constraints:
1 <= nodes <= 104parent.length == nodes0 <= parent[i] <= nodes - 1parent[0] == -1which indicates that0is the root.value.length == nodes-105 <= value[i] <= 105- The given input is guaranteed to represent a valid tree.