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.

这道题给了一棵二叉树,说了每个结点值均不相同,现在让删除一些结点,由于删除某些位置的结点会使原来的二叉树断开,从而会形成多棵二叉树,形成一片森林,让返回森林中所有二叉树的根结点。对于二叉树的题,十有八九都是用递归来做的,这道题也不例外,先来想一下这道题的难点在哪里,去掉哪些点会形成新树,显而易见的是,去掉根结点的话,左右子树若存在的话一定会形成新树,同理,去掉子树的根结点,也可能会形成新树,只有去掉叶结点时才不会生成新树,所以当前结点是不是根结点就很重要了,这个需要当作一个参数传入。由于需要知道当前结点是否需要被删掉,每次都遍历 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

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

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


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

(欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,试运营期间前五十位可享受半价优惠~)

×

Help us with donation