-
Notifications
You must be signed in to change notification settings - Fork 3
/
272.cpp
78 lines (76 loc) · 2.05 KB
/
272.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
/**
* Definition for a binary tree node.
* 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:
void getPredecessor(stack<TreeNode*>& pre) {
TreeNode* t = pre.top();
pre.pop();
t = t->left;
if (t) {
pre.push(t);
t = t->right;
while (t) {
pre.push(t);
t = t->right;
}
}
}
void getSuccessor(stack<TreeNode*>& suc) {
TreeNode* t = suc.top();
suc.pop();
t = t->right;
if (t) {
suc.push(t);
t = t->left;
while (t) {
suc.push(t);
t = t->left;
}
}
}
vector<int> closestKValues(TreeNode* root, double target, int k) {
stack<TreeNode*> pre;
stack<TreeNode*> suc;
vector<int> res;
while (root) {
if (root->val >= target) {
suc.push(root);
root = root->left;
}
else {
pre.push(root);
root = root->right;
}
}
while (k--) {
if (!pre.empty() && !suc.empty()) {
if (target - pre.top()->val < suc.top()->val - target) {
res.push_back(pre.top()->val);
getPredecessor(pre);
}
else {
res.push_back(suc.top()->val);
getSuccessor(suc);
}
}
else if (!pre.empty()) {
res.push_back(pre.top()->val);
getPredecessor(pre);
}
else {
res.push_back(suc.top()->val);
getSuccessor(suc);
}
}
return res;
}
};