标签:
There is a very simple idea to keep a max heap of size k and elements in the heap are sorted by their absolute difference from target. For the max heap, we will simply use the default priority_queue. Then we simply traverse the tree and push all its nodes to the heap while maintaining the size of heap not larger than k.
The code is as follows.
1 class Solution { 2 public: 3 vector<int> closestKValues(TreeNode* root, double target, int k) { 4 priority_queue<pair<double, int>> pq; 5 closestK(root, pq, target, k); 6 vector<int> closest; 7 while (!pq.empty()) 8 closest.push_back(pq.top().second), pq.pop(); 9 return closest; 10 } 11 private: 12 void closestK(TreeNode* node, priority_queue<pair<double, int>>& pq, double target, int k) { 13 if (!node) return; 14 pq.push(make_pair(abs(target - node -> val), node -> val)); 15 if (pq.size() > k) pq.pop(); 16 closestK(node -> left, pq, target, k); 17 closestK(node -> right, pq, target, k); 18 } 19 };
[LeetCode] Closest Binary Search Tree Value II
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4771342.html