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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 蝴蝶效應(yīng) 或許日后的發(fā)生的一切 改變只在與你的一句hello開始 便也是你對我的那一句hi 讓一切不一樣 驚起的 ...
    UnDOnE_LEE閱讀 917評論 0 0
  • 明天就是中秋佳節(jié)了,不知道現(xiàn)在的你有沒有正在趕回家過節(jié)的路上,或者是正在和家人朋友們團聚一桌共慶佳節(jié)呢?每逢佳節(jié)一...
    支離er閱讀 879評論 0 1
  • AFN (AFNetworking) 網(wǎng)絡(luò)請求中, 使用最多的就是AFNetworking框架, AFNetwor...
    鄰家菇?jīng)?/span>閱讀 2,256評論 0 6
  • 和程曦的見面約在了后天,沒見到人,我的心里已經(jīng)是滿滿的期待。聽他做的節(jié)目,是一種享受,很多都說到了我的心底。 這該...
    和這個世界溫柔的相處閱讀 256評論 0 6

友情鏈接更多精彩內(nèi)容