Skip to content

Commit

Permalink
solution for LC-1110-Delete Nodes and Return Forest
Browse files Browse the repository at this point in the history
  • Loading branch information
Trishit Chakraborty authored and Trishit Chakraborty committed Jul 17, 2024
1 parent 1fc8c7f commit 1362c6b
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions leetcode/1110-delete-nodes-and-return-forest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package leetcode;

import java.util.*;
class Solution {
static 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;
}
}
TreeNode helper(TreeNode root, HashSet<Integer> set, List<TreeNode> res){
if(root == null)
return null;
root.left = helper(root.left, set, res);
root.right = helper(root.right, set, res);
if(set.contains(root.val)){
if(root.left != null)
res.add(root.left);
if(root.right != null)
res.add(root.right);
root = null;
}
return root;
}
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<to_delete.length; i++){
set.add(to_delete[i]);
}
List<TreeNode> res = new ArrayList<>();
TreeNode node = helper(root, set, res);
if(node != null)
res.add(node);
return res;
}
}

0 comments on commit 1362c6b

Please sign in to comment.