题解 | #牛牛的二叉树问题#C++优先队列实现
牛牛的二叉树问题
https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e
#include <algorithm> class Solution { 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> res; auto cmp = [](std::pair<int, double>& a, std::pair<int, double>& b) { return a.second > b.second; }; priority_queue<std::pair<int, double>, vector<std::pair<int, double>>, decltype(cmp)> pr_que(cmp); queue<TreeNode*> que; que.push(root); while (!que.empty()) { auto node = que.front(); que.pop(); if (node->left) que.push(node->left); if (node->right) que.push(node->right); pr_que.push({node->val, abs(static_cast<double>(node->val) - target)}); } for (int i = 0; i < m; ++i) { res.push_back(pr_que.top().first); pr_que.pop(); } sort( res.begin(),res.end()); return res; } };