-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete Nodes And Return Forest.cpp
38 lines (29 loc) · 1.13 KB
/
Delete Nodes And Return Forest.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
TreeNode* helper(TreeNode* root, unordered_map<int, int> &toDel, unordered_map<TreeNode*, int> &mp){
if(!root) return NULL;
root->left = helper(root->left, toDel, mp);
root->right = helper(root->right, toDel, mp);
if(toDel.count(root->val)){
if(mp.count(root)) mp.erase(root);
//store roots of new components in map
if(root->left) mp[root->left]++;
if(root->right) mp[root->right]++;
//return null to break the tree as root is deleted
return NULL;
}
//if root is not present in to_delete return root
return root;
}
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
unordered_map<TreeNode*, int>mp;
unordered_map<int,int>toDel;
vector<TreeNode*>ans;
mp[root]++;
//store nodes values to be deleted in map
for(auto it : to_delete) toDel[it]++;
helper(root, toDel, mp);
for(auto it : mp) ans.push_back(it.first);
return ans;
}
};