码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Closest Binary Search Tree Value II

时间:2015-08-30 19:28:25      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!