Very Easy C++ Solution with Video Explanation
Video Explanation\nhttps://youtu.be/M7DdP7GUyJA\n\n# Intuition\nThe problem requires deleting certain nodes from a binary tree and returning the forest of remai
# Video Explanation\nhttps://youtu.be/M7DdP7GUyJA\n\n# Intuition\nThe problem requires deleting certain nodes from a binary tree and returning the forest of remaining trees. To achieve this, we need to traverse the tree and manage node deletions while maintaining the structure of the remaining nodes.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Store Nodes to Delete: First, we convert the to_delete list into a set for efficient lookup.\n2. Traverse and Delete: Use a recursive helper function deleteNode to traverse the tree.\n- If a node is to be deleted, its non-null children are added to the result list.\n- The node itself is set to NULL and deleted.\n3. Manage Resulting Trees: After traversing and modifying the tree, any remaining root node (not deleted) is added to the result list.\n4. Return Result: The final result is a list of tree roots, each representing a tree in the forest.\n\n# Complexity\n- Time complexity:$$O(n)$$ where N is the number of nodes in the tree, since we traverse each node once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$ for the recursion stack in the worst case (skewed tree), and for storing the result list and set.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\n    vector<TreeNode*>res;\n    unordered_set<int>st;\n    void deleteNode(TreeNode* &root){\n        if(root){\n            deleteNode(root->left);\n            deleteNode(root->right);\n            if(st.find(root->val)!=st.end()){\n                if(root->left) res.push_back(root->left);\n                if(root->right) res.push_back(root->right);\n                root=NULL;\n                \n            }\n        }\n    }\n\npublic:\n    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n        for(int i=0;i<to_delete.size();i++){\n            st.insert(to_delete[i]);\n        }\n        deleteNode(root);\n        if(root)res.push_back(root);\n        return res;\n    }\n};\n```
['C++']