-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1110.cpp
68 lines (58 loc) · 1.61 KB
/
1110.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
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
vector<TreeNode *> delNodes(TreeNode *root, vector<int> &to_delete) {
map<int, TreeNode *> segs;
segs[root->val] = root;
vector<TreeNode *> ret;
set<int> del;
for (auto d : to_delete) {
del.insert(d);
}
auto q = stack<TreeNode *>();
q.push(root);
while (!q.empty()) {
auto cur = q.top();
q.pop();
if (del.find(cur->val) != del.end()) {
segs.erase(cur->val);
if (cur->right) {
segs[cur->right->val] = cur->right;
}
if (cur->left) {
segs[cur->left->val] = cur->left;
}
}
if (cur->right) {
q.push(cur->right);
if (del.find(cur->right->val) != del.end()) {
cur->right = nullptr;
}
}
if (cur->left) {
q.push(cur->left);
if (del.find(cur->left->val) != del.end()) {
cur->left = nullptr;
}
}
}
for (auto i : segs) {
ret.push_back(i.second);
}
return ret;
}
};