题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
#include <set>
#include <utility>
using pii = pair<double, int>;
struct compare {
bool operator() (pii p1, pii p2){
return p1.first < p2.first;
}
};
class Solution {
private: multiset<pii,compare> res;
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target double浮点型
* @param m int整型
* @return int整型vector
*/
vector<int> findClosestElements(TreeNode* root, double target, int m) {
// write code here
vector<int> ans;
preOrder(root,target);
for(auto it = res.begin(); it != res.end() && m >0; it++, m--){
ans.emplace_back(it->second);
}
sort(ans.begin(), ans.end());
return ans;
}
void preOrder(TreeNode* root,double target){
if (root == nullptr) {
return;
}
res.insert({abs(root->val - target),root->val});
preOrder(root->left,target);
preOrder(root->right,target);
}
};
