[Tree] forest B020_ delete point (recursive)

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]]

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:

  1. 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.
  2. 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: O ( n ) O (n) ,
  • Space complexity: O ( n / l o g n ) O (n / logn) ,

Method Two:


Complexity Analysis

  • time complexity: O ( ) O() ,
  • Space complexity: O ( ) O() ,
Published 495 original articles · won praise 105 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/104882817