题目描述:
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.
Example:
Input: root = [4,2,5,1,3], target = 3.714286, and k = 2
4
/ \
2 5
/ \
1 3
Output: [4,3]
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
由于是求k个和目标值最接近的数,那么我们可以中序遍历二叉搜索树,这k个数必定是遍历序列中间的一段,那么用队列维护这k个数,每次遍历到一个节点都要和队首元素比较。
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
queue<int> q;
inorder(root,q,target,k);
vector<int> result;
while(!q.empty())
{
result.push_back(q.front());
q.pop();
}
return result;
}
void inorder(TreeNode* node, queue<int>& q, double target, int k)
{
if(node==NULL) return;
inorder(node->left,q,target,k);
if(q.size()<k) q.push(node->val);
else
{
if(abs((double)node->val-target)<abs((double)q.front()-target))
{
q.pop();
q.push(node->val);
}
}
inorder(node->right,q,target,k);
}
};
本文介绍了一种算法,用于在给定的非空二叉搜索树中找到k个最接近特定目标值的数值。通过中序遍历,利用队列维护最近的k个值,确保了结果的准确性。文章还探讨了在平衡BST中实现低于O(n)时间复杂度的可能性。
370

被折叠的 条评论
为什么被折叠?



