Closest Binary Search Tree Value II Posted on 2018-10-16 Descriptionhttps://leetcode.com/problems/closest-binary-search-tree-value-ii/description/ Solution123456789101112131415161718192021222324252627282930313233343536373839404142434445/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */struct cmp { bool operator () (pair<float, int>& A, pair<float, int>& B) { return A.first < B.first; }};class Solution {public: vector<int> closestKValues(TreeNode* root, double target, int k) { priority_queue<pair<float, int>, vector<pair<float, int>>, cmp> pq; inOrderTraverse(root, target, k, pq); vector<int> ret; while (!pq.empty()) { ret.push_back(pq.top().second); pq.pop(); } return ret; } void inOrderTraverse(TreeNode* root, double target, int k, priority_queue<pair<float, int>, vector<pair<float, int>>, cmp>& pq) { if (root == NULL) return; inOrderTraverse(root->left, target, k, pq); auto pa = make_pair(abs(root->val - target), root->val); if (pq.size() >= k) { if (pa.first < pq.top().first) { pq.pop(); pq.push(pa); } }else { pq.push(pa); } inOrderTraverse(root->right, target, k, pq); }};