Write a program to check the closest K nodes to target in BST?
vector closestKValues(TreeNode* root, double target, int k) {
vector res;
inorder(root, target, k, res);
return res;
}
void inorder(TreeNode *root, double target, int k, vector &res) {
if (!root) return;
inorder(root->left, target, k, res);
if (res.size() < k) res.push_back(root->val);
else if (abs(root->val - target) < abs(res[0] - target)) {
res.erase(res.begin());
res.push_back(root->val);
} else return;
inorder(root->right, target, k, res);
}
BY Best Interview Question ON 26 Jan 2020