1110. Delete Nodes And Return Forest
T: O(n)
S: O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
Set<TreeNode> result = new HashSet<>();
result.add(root);
Set<Integer> toDelete = new HashSet<>();
for (int d : to_delete) {
toDelete.add(d);
}
dfs(root, toDelete, result);
return new ArrayList(result);
}
private TreeNode dfs(TreeNode node, Set<Integer> toDelete, Set<TreeNode> result) {
if (node == null) {
return null;
}
TreeNode res = node;
if (toDelete.contains(node.val)) { // current node is deleting, so children become the root of new tree
if (node.left != null) {
result.add(node.left);
}
if (node.right != null) {
result.add(node.right);
}
res = null; // return null
result.remove(node); // remove itself in result
}
node.left = dfs(node.left, toDelete, result); // receive return value from children to link back to current node
node.right = dfs(node.right, toDelete, result);
return res;
}
}
/***
This question is not to delete a tree and move a node ...(not 450 -> quite hard!)
is breaking a tree into "several trees"! so become a forest! ->
!!!!key!!!: "so result only add "root" for each tree!""
ex: if only delete 2
1
2. 3
4 5. 6 7
then
4, 5 become 2 new roots for 2 trees
1 is still root (so that's why need to re-link, I mean this -> node.left = dfs(node.left, toDelete, result);
dfs will return null -> node.left = null)
so ans is [1,null, 3,6, 7] [4] [5]. (3 trees)
ex: if delete 1
then root become 2, 3 -> 2 trees
T: O(n)
S: O(n)
*/
Last updated