Leetcode 1110: Delete Nodes And Return Forest

grid47
grid47
Exploring patterns and algorithms
Jul 19, 2024 7 min read

Given the root of a binary tree, and a list of values to delete, your task is to remove the nodes with the given values. The resulting tree will become a forest, where each tree is a disjoint set of nodes. Return the roots of the trees in the remaining forest.
Problem
Approach
Steps
Complexity
Input: You are given the root of a binary tree and a list `to_delete` containing the values of the nodes to be removed. The tree is a binary tree with distinct node values.
Example: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Constraints:
• The number of nodes in the tree is at most 1000.
• Each node has a distinct value between 1 and 1000.
• The `to_delete` array contains distinct values between 1 and 1000.
Output: Return a list of trees in the forest (represented by their roots). The trees are in the remaining forest after deleting the specified nodes.
Example: Output: [[1,2,null,4],[6],[7]]
Constraints:
• The result should be the list of roots of the disjoint trees formed after deletion.
Goal: The goal is to remove nodes from the tree and form multiple disjoint trees. These disjoint trees should be collected and returned as a list of roots.
Steps:
• Create a set from the `to_delete` list for efficient lookups.
• Traverse the tree and delete the nodes found in `to_delete`.
• For each node that is a root of a new tree, add it to the result list.
• During traversal, ensure that after deletion, the children of deleted nodes are properly handled as roots of new trees.
Goal: The solution should handle the upper limits of input sizes efficiently.
Steps:
• The tree is guaranteed to have at most 1000 nodes.
• The `to_delete` array will contain distinct integers within the range of node values.
Assumptions:
• Nodes to be deleted will always exist in the tree.
• After deletion, the remaining trees are disjoint and valid.
Input: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Explanation: In this example, the nodes with values 3 and 5 will be removed from the tree. This results in three disjoint trees: one with root 1, another with root 6, and another with root 7.

Input: Input: root = [1,2,4,null,3], to_delete = [3]
Explanation: Here, node 3 is deleted, and the resulting tree will have a single tree rooted at 1 with child 2 and 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus