3
HashMap<Integer, List<TreeNode>> parent_val_child_nodes_map;4
HashMap<Integer, TreeNode> child_val_parent_node_map;6
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {9
parent_val_child_nodes_map = new HashMap<>();10
child_val_parent_node_map = new HashMap<>();15
// traverse to_delete to find those that do not have parent after deleting it16
List<TreeNode> res = new ArrayList<>();18
// actually deleting nodes19
for (int delete_val : to_delete) {21
// if the node has parent22
if (child_val_parent_node_map.containsKey(delete_val)) {23
TreeNode parent_node = child_val_parent_node_map.get(delete_val);24
if (parent_node.left != null && parent_node.left.val == delete_val) {25
parent_node.left = null;28
if (parent_node.right != null && parent_node.right.val == delete_val) {29
parent_node.right = null;34
// add root to the list first because root has no parent35
// only if root.val is not in to_delete36
if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) {40
// add other nodes that do not have parent41
for (int delete_val : to_delete) {42
if (parent_val_child_nodes_map.containsKey(delete_val)) {43
for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) {45
// make sure the add node is not in to_delete46
int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val;47
if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) {48
res.add(parent_val_child_nodes_map.get(delete_val).get(i));57
public void dfsFillMap(TreeNode root) {63
if (root.left != null) {64
parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<>());65
parent_val_child_nodes_map.get(root.val).add(root.left);67
child_val_parent_node_map.putIfAbsent(root.left.val, root);68
dfsFillMap(root.left);71
if (root.right != null) {72
parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<>());73
parent_val_child_nodes_map.get(root.val).add(root.right);75
child_val_parent_node_map.putIfAbsent(root.right.val, root);76
dfsFillMap(root.right);