LeetCode #272 - Closest Binary Search Tree Value II

本文介绍了一种算法,用于在给定的非空二叉搜索树中找到k个最接近特定目标值的数值。通过中序遍历,利用队列维护最近的k个值,确保了结果的准确性。文章还探讨了在平衡BST中实现低于O(n)时间复杂度的可能性。

题目描述:

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);
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值