1110. 删点成林
这道题就只需把每个树的根节点存到数列里面即可
自己一开始的想法 通过一个函数 将遍历到的空点置为null然后保存 可问题出在添加到原本的root 居然里面的点还没改
所以做错了
进一步改进
leetcode找了最接近我的想法的代码
class Solution { public List delNodes(TreeNode root, int[] to_delete) { List forest = new ArrayList(16); if (null == root) return forest; Set toDeleteSet = new HashSet(16); for (int e : to_delete) { toDeleteSet.add(e); } root = delNodes(root, forest, toDeleteSet); if (null != root) forest.add(root); return forest; } // 思路 // 如果是root待删除,则将其两个子指针 置空 // 如果是中间某节点待删除,则将两个子指针置空,同时需要将其父节点指向自己的连接置空。 // 递归解决。 public TreeNode delNodes(TreeNode root, List forest, Set toDeleteSet) { if (null == root) return null; root.left = delNodes(root.left, forest, toDeleteSet); root.right = delNodes(root.right, forest, toDeleteSet); if (toDeleteSet.contains(root.val)) { if (null != root.left&&!toDeleteSet.contains(root.left.val)) forest.add(root.left); if (null != root.right&&!toDeleteSet.contains(root.right.val))forest.add(root.right); return null; } return root; } }
class Solution {
public List delNodes(TreeNode root, int[] to_delete) { List res = new ArrayList(); boolean[] del = new boolean[1001]; for (int d : to_delete) { del[d] = true; } delete(root, null, true, del, res); return res; } private void delete(TreeNode root, TreeNode parent, boolean isLeft, boolean[] del, List res) { if (root == null) { return ; } boolean isDelete = del[root.val]; if (isDelete) { if (parent != null) { if (isLeft) { parent.left = null; } else { parent.right = null; } } } else { if (parent == null) { res.add(root); } } if (isDelete) { delete(root.left, null, true, del, res); delete(root.right, null, false, del, res); } else { delete(root.left, root, true, del, res); delete(root.right, root, false, del, res); } }
}
```