> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Delete Tree Nodes Python Solution with Tests

> Tested Python solution for LeetCode 1273 with 38 pytest cases. Generate a practice environment with lcpy.

LeetCode 1273, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Array](/catalog/topics/array), Tree DP. [View on LeetCode](https://leetcode.com/problems/delete-tree-nodes/description/).

Generate this problem as a practice environment: tested reference solution, 38 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1273   # by problem number
lcpy gen -s delete_tree_nodes   # by problem name
```

## 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](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1200-1299/1273.Delete%20Tree%20Nodes/images/1421_sample_1.png)

```
Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1]
Output: 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 \<= 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/delete_tree_nodes/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/delete_tree_nodes/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(nodes)
    # Space: O(nodes)
    def delete_tree_nodes(self, nodes: int, parent: list[int], value: list[int]) -> int:
        children: list[list[int]] = [[] for _ in range(nodes)]
        for i in range(1, nodes):
            children[parent[i]].append(i)

        # Iterative post-order keeps deep chains within the recursion limit.
        subtree_sums = [0] * nodes
        subtree_counts = [0] * nodes
        stack: list[tuple[int, bool]] = [(0, False)]
        while stack:
            node, processed = stack.pop()
            if processed:
                total, count = value[node], 1
                for child in children[node]:
                    total += subtree_sums[child]
                    count += subtree_counts[child]
                if total == 0:
                    count = 0
                subtree_sums[node], subtree_counts[node] = total, count
            else:
                stack.append((node, True))
                stack.extend((child, False) for child in children[node])
        return subtree_counts[0]
```

## Complexity

| Time | Space |
| - | - |
| O(nodes) | O(nodes) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.