/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <vector>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target double浮点型
* @param m int整型
* @return int整型vector
*/
vector<int> findClosestElements(TreeNode* root, double target, int m) {
unordered_map<TreeNode*,double> map;
vector<int> ans;
vector<pair<TreeNode*,double>> sta;
auto foreach = [&](auto foreach,TreeNode* root,double target){
if(root == nullptr){
return;
}
map[root] = abs(root->val - target);
foreach(foreach,root->left,target);
foreach(foreach,root->right,target);
};
foreach(foreach,root,target);
for(unordered_map<TreeNode*,double> :: iterator it = map.begin(); it != map.end(); it++){
sta.emplace_back(pair<TreeNode*,double>(it->first,it->second));
}
sort(sta.begin(),sta.end(),[&](pair<TreeNode*,double> v1, pair<TreeNode*,double> v2) -> bool{
return v1.second < v2.second;
});
for(int i = 0; i < m; i++){
ans.emplace_back(sta[i].first->val);
}
sort(ans.begin(),ans.end());
return ans;
}
};