-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1110. Delete Nodes And Return Forest.cpp
91 lines (72 loc) · 1.87 KB
/
1110. 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// method - 1
typedef pair<TreeNode*,bool> pi;
class Solution {
public:
TreeNode* help(TreeNode* root,unordered_set<int>& st,vector<TreeNode*>& ans)
{
//base case
if(!root)
return NULL;
//recursive calls
//and small calculation
TreeNode* a=help(root->left,st,ans);
TreeNode* b=help(root->right,st,ans);
root->left=a;
root->right=b;
if(st.count(root->val))
{
if(root->left)
ans.push_back(root->left);
if(root->right)
ans.push_back(root->right);
delete root;
return NULL;
}
return root;
}
// void traversal(TreeNode* root,vector<TreeNode*>& nodes)
// {
// //base case
// if(!root)
// return ;
// nodes.push_back(root);
// traversal(root->left,nodes);
// traversal(root->right,nodes);
// }
vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {
bool flag=0;
unordered_set<int> st;
for(auto& it:to_delete)
{
if(it==root->val)
flag=1;
st.insert(it);
}
vector<TreeNode*> roots;
help(root,st,roots);
if(flag)
return roots;
for(auto& it:roots)
{
if(it==root)
return roots;
}
roots.push_back(root);
// vector<vector<TreeNode*>> ans;
// for(auto& it:roots)
// {
// vector<TreeNode*> temp;
// traversal(it,temp);
// ans.push_back(temp);
// }
// return ans;
return roots;
}
};
// 1
// 2
// 3
// 4
// 1
// 2 4
// 3