ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

[LeetCode] 1110. Delete Nodes And Return Forest 删点成林

2021-05-09 03:01:52  阅读:222  来源: 互联网

标签:node 结点 Return res 1110 Forest return root delete



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 题目讲解汇总(持续更新中...)

标签:node,结点,Return,res,1110,Forest,return,root,delete
来源: https://www.cnblogs.com/grandyang/p/14747075.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有