-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solution for LC-1110-Delete Nodes and Return Forest
- 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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |