One, Title Description
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.
Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]
Output: [[1,2,null,4],[6],[7]]
![](https://img-blog.csdnimg.cn/20200315180440163.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTM5NTk5,size_16,color_FFFFFF,t_70)
Second, the problem solution
Method One: Sequence
* The first written, did not notice Java is passed by reference , directly off root is not feasible,
boolean[] del;
List<TreeNode> res;
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
res = new LinkedList<>();
del = new boolean[1001];
for (int d : to_delete) del[d] = true;
if (root != null) //1
res.add(root);
dfs(root);
return res;
}
void dfs(TreeNode root) {
if (root == null)
return;
dfs(root.left);
dfs(root.right);
if (del[root.val]) {
del[root.val] = false;
if (root.left != null) res.add(root.left);
if (root.right!= null) res.add(root.right);
root = null;
}
}
* Two error-prone points:
- You can not dfs at the beginning of the previous sentence if root is empty, because there may have been deleted root node. If after dfs deep search is not empty, it proves that he was not deleted node, which can be added into the result set res as root is the root of the tree.
- Because Java is passed by reference, the reference to the assignment does not change the reference point directly in the process, need to use the return value and then recursively through the end of the assignment.
boolean[] del;
List<TreeNode> res;
public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
del = new boolean[1050];
res = new LinkedList<>();
for (int d : to_delete) del[d] = true;
//if (root != null) 1
// res.add(root);
root = dfs(root);
if (root != null)
res.add(root);
return res;
}
private TreeNode dfs(TreeNode root) {
if (root == null) {
return null;
}
root.left = dfs(root.left);
root.right= dfs(root.right);
if (del[root.val]) {
if (root.left != null) res.add(root.left);
if (root.right!= null) res.add(root.right);
return null; //2
}
return root; //2
}
Complexity Analysis
- time complexity: ,
- Space complexity: ,
Method Two:
Complexity Analysis
- time complexity: ,
- Space complexity: ,