Skip to main content
LeetCode 1110, Medium. Topics: Array, Hash Table, Tree, Depth-First Search, Binary Tree. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 13 parametrized pytest cases, and a playground notebook:

Problem

Given the <code>root</code> of a binary tree, each node in the tree has a <strong>distinct</strong> value. After deleting all nodes with a value in <code>to_delete</code>, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return them in any order.

Examples

Example 1

Constraints

  • The number of nodes in the given tree is at most <code>1000</code>.
  • Each node has a <strong>distinct</strong> value between <code>1</code> and <code>1000</code>.
  • <code>to_delete.length <= 1000</code>
  • <code>to_delete</code> contains distinct values between <code>1</code> and <code>1000</code>.

Solution

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

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026