Given the root
of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete
, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
Example 1:
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]]
思路:这题可以用level order traverse,一遍记录,一遍收集下一层,一遍delete,但是写出来代码很多。可以work。
最牛逼的还是用divide and conquer, 假设左右两边都处理完了,怎么弄。
/**
* 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) {
List<TreeNode> list = new ArrayList<>();
HashSet<Integer> deleteSet = new HashSet<>();
for(int num: to_delete) {
deleteSet.add(num);
}
if(!deleteSet.contains(root.val)) {
list.add(root);
}
dfs(root, deleteSet, list);
return list;
}
private TreeNode dfs(TreeNode node, HashSet<Integer> deleteSet, List<TreeNode> list) {
if(node == null) {
return null;
}
node.left = dfs(node.left, deleteSet, list);
node.right = dfs(node.right, deleteSet, list);
if(deleteSet.contains(node.val)) {
if(node.left != null && !deleteSet.contains(node.left.val)) {
list.add(node.left);
}
if(node.right != null && !deleteSet.contains(node.right.val)) {
list.add(node.right);
}
return null;
} else {
// not contains;
return node;
}
}
}