forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest-nodes-queries-in-a-binary-search-tree.cpp
77 lines (73 loc) · 2.41 KB
/
closest-nodes-queries-in-a-binary-search-tree.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
// Time: O(n + qlogn)
// Space: O(n)
// iterative dfs, binary search
class Solution {
public:
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
const auto& iter_dfs = [&]() {
vector<int> inorder;
vector<pair<int, TreeNode *>> stk = {{1, root}};
while (!empty(stk)) {
const auto [step, node] = stk.back(); stk.pop_back();
if (step == 1) {
if (!node) {
continue;
}
stk.emplace_back(1, node->right);
stk.emplace_back(2, node);
stk.emplace_back(1, node->left);
} else if (step == 2) {
inorder.emplace_back(node->val);
}
}
return inorder;
};
const auto& inorder = iter_dfs();
vector<vector<int>> result;
for (const auto& q : queries) {
const auto cit = lower_bound(cbegin(inorder), cend(inorder), q);
if (cit == cend(inorder)) {
result.push_back({*prev(cit), -1});
} else if (*cit == q) {
result.push_back({*cit, *cit});
} else if (cit == cbegin(inorder)) {
result.push_back({-1, *cit});
} else {
result.push_back({*prev(cit), *cit});
}
}
return result;
}
};
// Time: O(n + qlogn)
// Space: O(n)
// dfs, binary search
class Solution2 {
public:
vector<vector<int>> closestNodes(TreeNode* root, vector<int>& queries) {
vector<int> inorder;
const function<void (TreeNode*)> dfs = [&](TreeNode *node) {
if (!node) {
return;
}
dfs(node->left);
inorder.emplace_back(node->val);
dfs(node->right);
};
dfs(root);
vector<vector<int>> result;
for (const auto& q : queries) {
const auto cit = lower_bound(cbegin(inorder), cend(inorder), q);
if (cit == cend(inorder)) {
result.push_back({*prev(cit), -1});
} else if (*cit == q) {
result.push_back({*cit, *cit});
} else if (cit == cbegin(inorder)) {
result.push_back({-1, *cit});
} else {
result.push_back({*prev(cit), *cit});
}
}
return result;
}
};