题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e
维护一个大小为m的大顶堆。
#include<bits/stdc++.h> /** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { private: priority_queue<pair<double, int>, vector<pair<double, int>>, less<>> que; vector<int> ret; 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 dfs(root, target, m); while(!que.empty()){ auto front = que.top(); que.pop(); ret.push_back(front.second); } sort(ret.begin(), ret.end()); return ret; } void dfs(TreeNode* root, double target, int m){ if(root==nullptr) return; que.push({abs(target-root->val), root->val}); while(que.size()>m) que.pop(); dfs(root->left, target, m); dfs(root->right, target, m); } };