Delete Nodes By Breaking Links And Form Forest Using DFS | Java | C++
Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/OlIbCYUR7Xw\n# Code\nJava\n\nclass Solution {\n    private Set<Integ
# Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/OlIbCYUR7Xw\n# Code\nJava\n```\nclass Solution {\n    private Set<Integer> schedForDel = new HashSet<>();\n    private List<TreeNode> rootNodes = new ArrayList<>();\n    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {\n        for(var node : to_delete){\n            schedForDel.add(node);\n        }\n        makeDeletions(root, true);\n        return rootNodes;\n    }\n    private void makeDeletions(TreeNode currNode, boolean isIndependent){\n        if(currNode == null)return;\n        if(!schedForDel.contains(currNode.val) && isIndependent){\n            rootNodes.add(currNode);\n        }\n        boolean makeChildIndep = false;\n        TreeNode leftChild = currNode.left, rightChild = currNode.right;\n        if(schedForDel.contains(currNode.val)){\n            makeChildIndep = true;\n        }\n        if(leftChild != null && schedForDel.contains(leftChild.val)){\n            currNode.left = null;\n        }\n        if(rightChild != null && schedForDel.contains(rightChild.val)){\n            currNode.right = null;\n        }\n        makeDeletions(leftChild, makeChildIndep);\n        makeDeletions(rightChild, makeChildIndep);\n    }\n}\n```\nC++\n```\nclass Solution {\nprivate:\n    unordered_set<int> schedForDel;\n    vector<TreeNode*> rootNodes;\n\npublic:\n    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n        for (auto node : to_delete) {\n            schedForDel.insert(node);\n        }\n        makeDeletions(root, true);\n        return rootNodes;\n    }\n\nprivate:\n    void makeDeletions(TreeNode* currNode, bool isIndependent) {\n        if (currNode == nullptr) return;\n\n        if (schedForDel.find(currNode->val) == schedForDel.end() && isIndependent) {\n            rootNodes.push_back(currNode);\n        }\n\n        bool makeChildIndep = false;\n        TreeNode* leftChild = currNode->left;\n        TreeNode* rightChild = currNode->right;\n\n        if (schedForDel.find(currNode->val) != schedForDel.end()) {\n            makeChildIndep = true;\n        }\n\n        if (leftChild != nullptr && schedForDel.find(leftChild->val) != schedForDel.end()) {\n            currNode->left = nullptr;\n        }\n        if (rightChild != nullptr && schedForDel.find(rightChild->val) != schedForDel.end()) {\n            currNode->right = nullptr;\n        }\n\n        makeDeletions(leftChild, makeChildIndep);\n        makeDeletions(rightChild, makeChildIndep);\n    }\n};\n```\n
['Array', 'Hash Table', 'Tree', 'Depth-First Search', 'Binary Tree', 'C++', 'Java']