Skip to main content
LeetCode 1273, Medium. Topics: Tree, Depth-First Search, Breadth-First Search, Array, Tree DP. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 38 parametrized pytest cases, and a playground notebook:

Problem

A tree rooted at node 0 is given as follows: <ul> <li>The number of nodes is <code>nodes</code>;</li> <li>The value of the <code>i<sup>th</sup></code> node is <code>value[i]</code>;</li> <li>The parent of the <code>i<sup>th</sup></code> node is <code>parent[i]</code>.</li> </ul> <p>Remove every subtree whose sum of values of nodes is zero.</p> <p>Return <em>the number of the remaining nodes in the tree</em>.</p>

Examples

Example 1

Constraints

  • 1 <= nodes <= 10^4
  • parent.length == nodes
  • 0 <= parent[i] <= nodes - 1
  • parent[0] == -1 which indicates that 0 is the root.
  • value.length == nodes
  • -10^5 <= value[i] <= 10^5
  • The given input is <strong>guaranteed</strong> to represent a <strong>valid tree</strong>.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026