Problem 913
Delete Nodes And Return Forest
Medium · 20 pts · Tree, Depth-First Search, Hash Table
Problem
The binary tree has distinct values. Delete every node whose value is in the list TO_DELETE. What remains is a forest of separate trees: a node becomes the root of a new tree when it is kept but its parent was deleted (or it is the original root). Print the number of trees, then each tree in level order on its own line, ordering the trees by their root value. A post-order traversal can detach children before deciding about the parent.
Input
The first line contains M, then a line with the M values to delete. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children. All values are distinct.
Output
Print the number of trees, then each tree's level-order tokens (null for missing children, no trailing nulls) on its own line, ordered by root value.
Constraints
1 <= number of nodes <= 1000; 1 <= value <= 1000; values are distinct; 0 <= M <= 1000
Example input
2 3 5 7 1 2 3 4 5 6 7
Example output
3 1 2 null 4 6 7
Explanation
Deleting 3 and 5 from 1 2 3 4 5 6 7 leaves three trees: 1 2 null 4 (2 keeps its child 4), 6 and 7. Ordered by root value they are printed as 1 2 null 4, then 6, then 7.