给定一棵非空二叉搜索树以及一个target值,找到 BST 中最接近给定值的 k
个数。
样例
样例 1:
输入:
{1}
0.000000
1
输出:
[1]
解释:
二叉树 {1},表示如下的树结构:
1
样例 2:
输入:
{3,1,4,#,2}
0.275000
2
输出:
[1,2]
解释:
二叉树 {3,1,4,#,2},表示如下的树结构:
3
/ \
1 4
\
2
挑战
假设是一棵平衡二叉搜索树,你可以用时间复杂度低于O(n)的算法解决问题吗( n 为节点个数)?
注意事项
- 给出的target值为浮点数
- 你可以假设
k
总是合理的,即k ≤ 总节点数
- 我们可以保证给出的 BST 中只有
唯一
一个最接近给定值的 k 个值的集合
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
bool cmp(pair<int,double> a, pair<int,double> b) {
return a.second < b.second;
}
class Solution {
public:
/**
* @param root: the given BST
* @param target: the given target
* @param k: the given k
* @return: k values in the BST that are closest to the target
*/
vector<int> nums;
vector<int> closestKValues(TreeNode * root, double target, int k) {
// write your code here
bianli(root);
vector< pair<int,double> > vec;
sort(vec.begin(),vec.end(),cmp);
vector<int> ret;
for(int i = 0; i < nums.size(); i++)
{
double tmp = fabs(target-nums[i]);
vec.push_back( pair<int,double>(nums[i],tmp) );
}
sort(vec.begin(),vec.end(),cmp);
for(int i = 0; i < k; i++)
{
ret.push_back(vec[i].first);
}
return ret;
}
void bianli(TreeNode * root)
{
if(root != NULL)
{
nums.push_back(root->val);
bianli(root->left);
bianli(root->right);
}
}
};