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]]
Example 2:
Input: root = [1,2,4,null,3], to_delete = [3]
Output: [[1,2,4]]
Constraints:
- The number of nodes in the given tree is at most
1000
. - Each node has a distinct value between
1
and1000
. to_delete.length <= 1000
to_delete
contains distinct values between1
and1000
.
這道題給了一棵二叉樹,說了每個結點值均不相同,現在讓刪除一些結點,由於刪除某些位置的結點會使原來的二叉樹斷開,從而會形成多棵二叉樹,形成一片森林,讓返回森林中所有二叉樹的根結點。對於二叉樹的題,十有八九都是用遞歸來做的,這道題也不例外,先來想一下這道題的難點在哪里,去掉哪些點會形成新樹,顯而易見的是,去掉根結點的話,左右子樹若存在的話一定會形成新樹,同理,去掉子樹的根結點,也可能會形成新樹,只有去掉葉結點時才不會生成新樹,所以當前結點是不是根結點就很重要了,這個需要當作一個參數傳入。由於需要知道當前結點是否需要被刪掉,每次都遍歷 to_delete 數組顯然不高效,那就將其放入一個 HashSet 中,從而到達常數級的搜索時間。這樣遞歸函數就需要四個參數,當前結點,是否是根結點的布爾型變量,HashSet,還有結果數組 res。在遞歸函數中,首先判空,然后判斷當前結點值是否在 HashSet,用一個布爾型變量 deleted 來記錄。若當前是根結點,且不需要被刪除,則將這個結點加入結果 res 中。然后將左子結點賦值為對左子結點調用遞歸函數的返回值,右子結點同樣賦值為對右子結點調用遞歸的返回值,最后判斷當前結點是否被刪除了,是的話返回空指針,否則就返回當前指針,這樣的話每棵樹的根結點都在遞歸的過程中被存入結果 res 中了,參見代碼如下:
class Solution {
public:
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
vector<TreeNode*> res;
unordered_set<int> st(to_delete.begin(), to_delete.end());
helper(root, true, st, res);
return res;
}
TreeNode* helper(TreeNode* node, bool is_root, unordered_set<int>& st, vector<TreeNode*>& res) {
if (!node) return nullptr;
bool deleted = st.count(node->val);
if (is_root && !deleted) res.push_back(node);
node->left = helper(node->left, deleted, st, res);
node->right = helper(node->right, deleted, st, res);
return deleted ? nullptr : node;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1110
參考資料:
https://leetcode.com/problems/delete-nodes-and-return-forest/
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/328860/Simple-Java-Sol