Delete Flagged Nodes and Return the Remaining Forest of Trees
Last updated: November 29, 2026
Quick Overview
Given a binary tree of service nodes with unique IDs and a set of IDs to decommission, delete those nodes. Return the roots of the trees that remain.
0
0
0 solved
Given a binary tree of service nodes with unique IDs and a set of IDs to decommission, delete those nodes. Return the roots of the trees that remain.
Common in Google onsites because it requires deciding what information flows down (is my parent deleted?) and what flows up (should my parent unlink me?). The interviewer looks for a single pass instead of repeated searches.
What the Interviewer Expects
- Use a set for O(1) membership checks
- Pass down whether the current node would become a new root
- Return None upward for deleted nodes so parents unlink them
- Collect roots in one traversal
- Handle deletion of the original root
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the forest sorted by subtree size.
- Make it iterative.
- What if deletions arrive one at a time and you must update the forest incrementally?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: root with unique values and a list to_delete. Output: list of remaining tree roots in any order. The tree is mutated in place: deleted nodes are unlinked from parents....
High-Level Design
Recurse with a flag is_root telling a node whether its parent is gone (or it is the original root). At each node, compute deleted = val in to_delete. If the node is kept and is_root is true, it ...