7. Closest Binary Search Tree Value II

Link to the problem

Description

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.
    Follow up:
    Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

Example

Input: [2, 1, 3], target = 1.5, k = 2, Output: [1, 2]

Idea

First do an inorder traversal, then find the k closest values by finding the pivot, and run the merge in merge sort.

Solution

class Solution {
private:
    void inorderTraversal(TreeNode *root, vector<int> &values) {
        if (root) {
            inorderTraversal(root->left, values);
            values.push_back(root->val);
            inorderTraversal(root->right, values);
        }
    }

public:
    vector<int> closestKValues(TreeNode* root, double target, int k) {
        vector<int> values;
        inorderTraversal(root, values);
        vector<int> rtn;
        int n = values.size();
        int right = 0;
        while (right < n && values[right] < target) right++;
        int left = right - 1;
        while (rtn.size() < k) {
            if (left >= 0 && right < n) {
                if (abs((double) values[left] - target) < abs((double) values[right] - target)) {
                    rtn.push_back(values[left--]);
                } else {
                    rtn.push_back(values[right++]);
                }
            } else if (left >= 0) {
                rtn.push_back(values[left--]);
            } else {
                rtn.push_back(values[right++]);
            }
        }
        return rtn;
    }
};

68 / 68 test cases passed.
Runtime: 13 ms

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 蝴蝶效应 或许日后的发生的一切 改变只在与你的一句hello开始 便也是你对我的那一句hi 让一切不一样 惊起的 ...
    UnDOnE_LEE阅读 798评论 0 0
  • 明天就是中秋佳节了,不知道现在的你有没有正在赶回家过节的路上,或者是正在和家人朋友们团聚一桌共庆佳节呢?每逢佳节一...
    支离er阅读 783评论 0 1
  • AFN (AFNetworking) 网络请求中, 使用最多的就是AFNetworking框架, AFNetwor...
    邻家菇凉阅读 2,192评论 0 6
  • 和程曦的见面约在了后天,没见到人,我的心里已经是满满的期待。听他做的节目,是一种享受,很多都说到了我的心底。 这该...
    和这个世界温柔的相处阅读 227评论 0 6