Leetcode 272 Solution

This article provides solution to leetcode question 272 (closest-binary-search-tree-value-ii)

https://leetcode.com/problems/closest-binary-search-tree-value-ii

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    deque<int> q;
public:
    void findClosestKValues(TreeNode* root, double target, int k)
    {
        if (root == NULL)
            return;

        findClosestKValues(root->left, target, k);

        if (q.size() < k)
            q.push_back(root->val);
        else if (abs(q.front() - target) > abs(root->val - target))
        {
            q.pop_front();
            q.push_back(root->val);
        }
        else
            return;

        findClosestKValues(root->right, target, k);
    }

    vector<int> closestKValues(TreeNode* root, double target, int k) {
        findClosestKValues(root, target, k);
        vector<int> res;

        while (q.empty() == false)
        {
            res.push_back(q.front());
            q.pop_front();
        }

        return res;
    }
};