Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1273: Delete Tree Nodes

In this guide, we solve Leetcode #1273 Delete Tree Nodes in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

A tree rooted at node 0 is given as follows: The number of nodes is nodes; The value of the ith node is value[i]; The parent of the ith node is parent[i]. Remove every subtree whose sum of values of nodes is zero.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Tree, Depth-First Search, Breadth-First Search, Array

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: nodes = 7, parent = [-1,0,0,1,2,2,2], value = [1,-2,4,0,-2,-1,-1] Output: 2

Python Solution

class Solution: def deleteTreeNodes(self, nodes: int, parent: List[int], value: List[int]) -> int: def dfs(i): s, m = value[i], 1 for j in g[i]: t, n = dfs(j) s += t m += n if s == 0: m = 0 return (s, m) g = defaultdict(list) for i in range(1, nodes): g[parent[i]].append(i) return dfs(0)[1]

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n). The space complexity is O(n)O(n)O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy