1. 程式人生 > 實用技巧 >[LeetCode] 1110. Delete Nodes And Return Forest

[LeetCode] 1110. Delete Nodes And Return Forest

Given therootof a binary tree, each node in the tree has a distinct value.

After deletingall nodes with a value into_delete, we are left with a forest (adisjoint 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]]

Constraints:

  • The number of nodes in the given tree is at most1000.
  • Each node has a distinct value between1and1000.
  • to_delete.length <= 1000
  • to_deletecontains distinct values between1and1000.

刪點成林。題意是給一棵二叉樹和一個to_delete陣列,請你從樹中刪除to_delete中出現的節點,返回一個森林。

這道題BFS和DFS都能做,我這裡提供一個BFS的做法。首先用一個hashset儲存所有需要刪除的節點。接著開始遍歷樹的每一個節點,遍歷的方式還是跟層序遍歷類似。從queue中彈出節點的時候,要做如下幾件事情

  • 如果這個節點是需要被刪除的節點,需要從結果集裡面刪除這個節點
  • 如果被刪除的節點有孩子節點,需要把孩子節點加入結果集,因為他們沒有父節點了,他們現在是自己這個子樹的根節點了
  • 當前節點如果有左孩子和右孩子,則分別加入queue繼續下面的遍歷,同時遍歷的時候檢查他們是否需要被刪除,如果需要,在把他們放入queue之後需要斷開他們和父節點的連線

時間O(n)

空間O(n)

Java實現

 1 class Solution {
 2     public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
 3         List<TreeNode> res = new
ArrayList<>(); 4 Queue<TreeNode> queue = new LinkedList<>(); 5 queue.offer(root); 6 res.add(root); 7 HashSet<Integer> set = new HashSet<>(); 8 for (int node : to_delete) { 9 set.add(node); 10 } 11 12 while (!queue.isEmpty()) { 13 TreeNode cur = queue.poll(); 14 if (set.contains(cur.val)) { 15 res.remove(cur); 16 if (cur.left != null) { 17 res.add(cur.left); 18 } 19 if (cur.right != null) { 20 res.add(cur.right); 21 } 22 } 23 if (cur.left != null) { 24 queue.offer(cur.left); 25 if (set.contains(cur.left.val)) { 26 cur.left = null; 27 } 28 } 29 if (cur.right != null) { 30 queue.offer(cur.right); 31 if (set.contains(cur.right.val)) { 32 cur.right = null; 33 } 34 } 35 } 36 return res; 37 } 38 }

LeetCode 題目總結