Java | Beats 99.67% | Well Explained
When and from where to remove the node??  I knew that if I have to delete any node I have to assign it to null. But how could I do that the same time I am check
1. When and from where to remove the node??  I knew that if I have to delete any node I have to assign it to null. But how could I do that the same time I am checking if the node has to be deleted or not. We can\'t do that. What we have to do is to get to know if the leftNode/rightNode is deleted or not. If yes then assign the current node\'s left/right node to null. \n2. When to add the node?? We have to add the node only when the current node is going to be deleted. So if the left node is not deleted add it to the list. Same is the scenario for right node.\n\n** The first solution I thought is to return a boolean value if the node will be deleted. We could do that too. But this is the cleaner code **\n\nDownvote if you don\'t like the explanation. Upvote if do like the explanation.\n\n\n```\nclass Solution {\n    \n    HashSet<Integer> set = new HashSet<>();\n    List<TreeNode> list = new ArrayList<>();\n    \n    public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {\n        for(int val: to_delete){\n            set.add(val);\n        }\n        helper(root);\n        if(!set.contains(root.val)){\n            list.add(root);\n        }\n        return list;\n    }\n    \n    public TreeNode helper(TreeNode node){\n        if(node == null)\n            return null;\n        \n        node.left = helper(node.left);\n        node.right = helper(node.right);\n        \n        if(set.contains(node.val)){\n            if(node.left != null){\n                list.add(node.left);\n            }\n            if(node.right != null){\n                list.add(node.right);\n            }\n            return null;\n        }\n        return node;\n    }\n}\n```
['Recursion', 'Java']