LeetCode - Closest Binary Search Tree Value II

解法一: 用inorder排序

class Solution {
public:
    vector closestKValues(TreeNode* root, double target, int k) {
        if(!root) return {};
        vector insequence;
        vector res;
        inorder(root, insequence);
        
        // get the closest element index
        double diff = numeric_limits::max();
        int index = -1;
        for(int i=0;i=0 && abs(insequence[l]-target)<=abs(insequence[r]-target)){
                res.push_back(insequence[l]);
                l--;
            }else if(r& 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 closestKValues(TreeNode* root, double target, int k) {
        if(!root) return {};
        vector res;
        inorder(root, target, k, res);
        return res;
    }
    void inorder(TreeNode* root, double& target, int& k, vector& res){
        if(!root) return;
        inorder(root->left, target, k, res);
        if(res.size()val);
        else if(abs(root->val-target)val);
        }else return;
        inorder(root->right, target, k, res);
    }
    
};

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

 

 

 

 

你可能感兴趣的:(LeetCode)