forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Closest_Binary_Search_Tree_Value_II.cpp
38 lines (37 loc) · 1.09 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
/**
* 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 {
void closestKValuesRecur(TreeNode* root, double target, int k, priority_queue<pair<double, int>>& Q) {
double diff = abs(root->val - target);
if(Q.size() < k) {
Q.push(make_pair(diff, root->val));
} else if(diff < Q.top().first) {
Q.pop();
Q.push(make_pair(diff, root->val));
}
if(root->left) {
closestKValuesRecur(root->left, target, k, Q);
}
if(root->right) {
closestKValuesRecur(root->right, target, k, Q);
}
}
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
priority_queue <pair<double, int>> Q;
vector<int> result;
closestKValuesRecur(root, target, k, Q);
while(!Q.empty()) {
result.push_back(Q.top().second);
Q.pop();
}
return result;
}
};