1.

Write a program to check the closest K nodes to target in BST?

Answer»

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);
}

 



Discussion

No Comment Found