解法一: 用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然后远离,可以利用这个特性来完成这个道题