算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 最接近的二叉搜索树值II,我们先来看题面:
https://leetcode-cn.com/problems/closest-binary-search-tree-value-ii/
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的 k 个值。
注意:
给定的目标值 target 是一个浮点数
你可以默认 k 值永远是有效的,即 k ≤ 总结点数
题目保证该二叉搜索树中只会存在一种 k 个值集合最接近目标值
示例
示例:
输入: root = [4,2,5,1,3],目标值 = 3.714286,且 k = 2
4
/ \
2 5
/ \
1 3
输出: [4,3]
解题
https://michael.blog.csdn.net/article/details/107232667
使用stack,中序遍历bst,是有序的
将差值最小的k个元素的<差值,自身值>
插入优先队列
队列满了k个,且差值为正,且大于堆顶,可以提前结束
struct cmp
{
bool operator()(vector<double>& a, vector<double>& b)
{
return a[0] < b[0];//差值大的在上
}
};
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
stack<TreeNode*> s;
priority_queue<vector<double>, vector<vector<double>>, cmp> q;
TreeNode* cur;
while(root || !s.empty())
{
while(root)
{
s.push(root);
root = root->left;
}
cur = s.top();
s.pop();
root = cur->right;
if(q.size() < k)
q.push({fabs(cur->val-target), double(cur->val)});
else if(q.size()==k && q.top()[0] > fabs(cur->val-target))
{ //有更小的差值
q.pop();
q.push({fabs(cur->val-target), double(cur->val)});
}
if(q.size()==k && cur->val-target >= q.top()[0])
break;
}
vector<int> ans(k);
int i = 0;
while(!q.empty())
{
ans[i++] = q.top()[1];
q.pop();
}
return ans;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: