LeetCode - Closest Binary Search Tree Value II

解法一: 用inorder排序

class Solution {
public:
    vector<int> closestKValues(TreeNode* root, double target, int k) {
        if(!root) return {};
        vector<int> insequence;
        vector<int> res;
        inorder(root, insequence);
        
        // get the closest element index
        double diff = numeric_limits<double>::max();
        int index = -1;
        for(int i=0;i<insequence.size();i++){
            double cur = abs(insequence[i]-target);        // use double instead of int
            if(cur<=diff){
                diff = cur;
                index = i;
            }
        }
        
        res.push_back(insequence[index]);
        int l=index-1, r=index+1;
        for(int i=0;i<k-1;i++){                            // l or r, one of them may be valid
            if(l>=0 && abs(insequence[l]-target)<=abs(insequence[r]-target)){
                res.push_back(insequence[l]);
                l--;
            }else if(r<insequence.size()){
                res.push_back(insequence[r]);
                r++;
            }
        }
        
        return res;
    }
    void inorder(TreeNode* root, vector<int>& insequence){
        if(!root) return;
        inorder(root->left, insequence);
        insequence.push_back(root->val);
        inorder(root->right, insequence);
    }
    
};

1. use inorder to get the ascending sequence

2. get the closest element

3. get the next closest element

解法二:inorder中间完成

class Solution {
public:
    vector<int> closestKValues(TreeNode* root, double target, int k) {
        if(!root) return {};
        vector<int> res;
        inorder(root, target, k, res);
        return res;
    }
    void inorder(TreeNode* root, double& target, int& k, vector<int>& res){
        if(!root) return;
        inorder(root->left, target, k, res);
        if(res.size()<k) res.push_back(root->val);
        else if(abs(root->val-target)<abs(res[0]-target)){
            res.erase(res.begin());
            res.push_back(root->val);
        }else return;
        inorder(root->right, target, k, res);
    }
    
};

inorder排序过程,接近target然后远离,可以利用这个特性来完成这个道题

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值