Leetcode Problem 1110. Delete Nodes And Return Forest

1110. Delete Nodes And Return Forest

Leetcode Solutions

Recursion with Parent Notification

  1. Convert the to_delete list into a set for efficient deletion checks.
  2. Define a recursive function walk that accepts a node and a boolean indicating if the parent exists.
  3. If the current node is None, return None.
  4. If the current node is in the to_delete set, recursively call walk on its children with parent_exist set to False, and return None.
  5. If the current node is not in the to_delete set and the parent does not exist, add the current node to the result list.
  6. Recursively call walk on the left and right children of the current node with parent_exist set to True.
  7. Return the current node if it's not deleted, otherwise return None.
  8. Call the walk function with the root node and parent_exist set to False.
  9. Return the result list containing the roots of the trees in the remaining forest.
UML Thumbnail

Iterative with Queue and Map

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...