generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.cpp
50 lines (42 loc) · 1.31 KB
/
solution.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
#include <unordered_set>
#include <vector>
class Solution {
public:
std::vector<TreeNode*> delNodes(
TreeNode* root, std::vector<int>& to_delete) {
std::unordered_set<int> deleteList{};
for (const auto val : to_delete) {
deleteList.insert(val);
}
std::vector<TreeNode*> trees{};
const bool deleted = collectTrees(trees, root, deleteList);
if (!deleted) trees.push_back(root);
return trees;
}
bool collectTrees(
std::vector<TreeNode*>& trees,
TreeNode* node,
std::unordered_set<int>& deleteList) {
if (deleteList.contains(node->val)) {
if (node->right != nullptr) {
const bool deleted = collectTrees(trees, node->right, deleteList);
if (!deleted) trees.push_back(node->right);
}
if (node->left != nullptr) {
const bool deleted = collectTrees(trees, node->left, deleteList);
if (!deleted) trees.push_back(node->left);
}
return true;
} else {
if (node->right != nullptr) {
const bool deleted = collectTrees(trees, node->right, deleteList);
if (deleted) node->right = nullptr;
}
if (node->left != nullptr) {
const bool deleted = collectTrees(trees, node->left, deleteList);
if (deleted) node->left = nullptr;
}
return false;
}
}
};