AlgoMaster Logo

Delete Nodes And Return Forest

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive DFS Approach

Intuition:

The problem requires us to return a forest of trees by deleting certain nodes from a binary tree. We can tackle this problem using a recursive approach. The primary idea is to traverse the tree using DFS (Depth First Search) and make decisions at each node whether it is to be deleted or retained.

  1. For each node, recursively decide for its left and right children whether they need to be deleted.
  2. If a node is to be deleted, its children are added to the result list of roots if they are non-null.
  3. If a node is not deleted, and it is a root (i.e., the start of recursion), add it to the result list of roots.

Steps:

  • Start from the root of the tree.
  • Use recursion to traverse the tree.
  • At each recursive call, check if the current node is in the delete list.
  • If it is, add its children to the forest if they exist.
  • If not, keep traversing, possibly marking this node to remain as part of an existing tree.

Code:

2. Optimized Recursive DFS with Set

Intuition:

This approach enhances the first solution by using a HashSet to store nodes that need to be deleted, making the check for deletions (O(1)) on average. This makes it slightly more optimal for larger sets of nodes to be deleted.

Same steps as above, but the check for deletion is turned into an (O(1)) operation by using a Set data structure.

Code: