题解 | #牛牛的二叉树问题#

牛牛的二叉树问题

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 <queue>
 #include <algorithm>

class mypair {
	int first;
	double second;
public:
	bool operator<(const mypair& other) const {
		return this->second < other.second;  // left > right
	}
    mypair(int a, double b):first(a), second(b){};
    double get_second() const {return second;};
    int get_first() const {return first;};
};

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param target double浮点型 
     * @param m int整型 
     * @return int整型vector
     */
    void bfs(TreeNode* root, priority_queue<mypair>& heapmax, int& m, double& target){
        if (root == nullptr) return;
        if(heapmax.size() < m) {
            heapmax.emplace(root->val, abs(root->val - target));
        }
        else{
            // compair
            double temp = abs(root->val - target);
            if(temp < heapmax.top().get_second()){
                heapmax.pop();
                heapmax.emplace(root->val, temp);
            }
        }
        bfs(root->left, heapmax, m, target);
        bfs(root->right, heapmax, m, target);
     }
    vector<int> findClosestElements(TreeNode* root, double target, int m) {
        // write code here
        priority_queue<mypair> heapmax;
        vector<int> res;
        bfs(root, heapmax, m, target);
        for(int i = 0; i < m; ++i){
            res.push_back(heapmax.top().get_first());
            heapmax.pop();
        }
        sort(res.begin(), res.end());
        return res;
    }
};

全部评论

相关推荐

昨天 11:42
江西农业大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务