# 1110. Delete Nodes And Return Forest

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` and `1000`.
• `to_delete.length <= 1000`
• `to_delete` contains distinct values between `1` and `1000`.

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

https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/328853/JavaC%2B%2BPython-Recursion-Solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation