forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest-binary-search-tree-value-ii.cpp
70 lines (65 loc) · 2.55 KB
/
closest-binary-search-tree-value-ii.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
// Time: O(h + k)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
// The forward or backward iterator.
const auto backward = [](const vector<TreeNode*>& s) { return s.back()->left; };
const auto forward = [](const vector<TreeNode*>& s) { return s.back()->right; };
const auto closest = [&target](const TreeNode* a, const TreeNode* b) {
return abs(a->val - target) < abs(b->val - target);
};
// Build the stack to the closest node.
vector<TreeNode*> s;
while (root) {
s.emplace_back(root);
root = target < root->val ? root->left : root->right;
}
// Get the stack to the next smaller node.
vector<TreeNode*> forward_stack(s.cbegin(), next(min_element(s.cbegin(), s.cend(), closest)));
vector<TreeNode*> backward_stack(forward_stack);
nextNode(backward_stack, backward, forward);
// Get the closest k values by advancing the iterators of the stacks.
vector<int> result;
for (int i = 0; i < k; ++i) {
if (!forward_stack.empty() &&
(backward_stack.empty() || closest(forward_stack.back(), backward_stack.back()))) {
result.emplace_back(forward_stack.back()->val);
nextNode(forward_stack, forward, backward);
} else if (!backward_stack.empty() &&
(forward_stack.empty() || !closest(forward_stack.back(), backward_stack.back()))) {
result.emplace_back(backward_stack.back()->val);
nextNode(backward_stack, backward, forward);
}
}
return result;
}
// Helper to make a stack to the next node.
template<typename T, typename U>
void nextNode(vector<TreeNode*>& s, const T& child1, const U& child2) {
if (!s.empty()) {
if (child2(s)) {
s.emplace_back(child2(s));
while (child1(s)) {
s.emplace_back(child1(s));
}
} else {
auto child = s.back();
s.pop_back();
while (!s.empty() && child == child2(s)) {
child = s.back();
s.pop_back();
}
}
}
}
};