# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestKValues(self, root, target, k):
def inorder(node):
if not node:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
vals = inorder(root)
vals.sort(key=lambda x: abs(x - target))
return vals[:k]
// 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 {
public:
vector closestKValues(TreeNode* root, double target, int k) {
vector vals;
inorder(root, vals);
sort(vals.begin(), vals.end(), [target](int a, int b) {
return abs(a - target) < abs(b - target);
});
return vector(vals.begin(), vals.begin() + k);
}
private:
void inorder(TreeNode* node, vector& vals) {
if (!node) return;
inorder(node->left, vals);
vals.push_back(node->val);
inorder(node->right, vals);
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution {
public List closestKValues(TreeNode root, double target, int k) {
List vals = new ArrayList<>();
inorder(root, vals);
vals.sort((a, b) -> Double.compare(Math.abs(a - target), Math.abs(b - target)));
return vals.subList(0, k);
}
private void inorder(TreeNode node, List vals) {
if (node == null) return;
inorder(node.left, vals);
vals.add(node.val);
inorder(node.right, vals);
}
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} target
* @param {number} k
* @return {number[]}
*/
var closestKValues = function(root, target, k) {
const vals = [];
function inorder(node) {
if (!node) return;
inorder(node.left);
vals.push(node.val);
inorder(node.right);
}
inorder(root);
vals.sort((a, b) => Math.abs(a - target) - Math.abs(b - target));
return vals.slice(0, k);
};
Given the root of a binary search tree (BST), a target
value, and an integer k
, find the k
values in the BST that are closest to the target
. The result can be returned in any order. Each value in the BST is unique, and you should not reuse elements. There is always at least one valid solution.
root
(the root node of the BST), target
(a floating-point number), k
(an integer)k
integers from the BST closest to target
To solve this problem, we need to identify which k
node values in the BST are numerically closest to the given target
value. The most straightforward (brute-force) approach would be to traverse the entire tree, collect all values, compute their distance to the target, sort them by this distance, and pick the closest k
.
However, since the input is a BST, we can consider optimizations. For example, an in-order traversal yields values in sorted order, which can help us efficiently find the closest values using two pointers or a sliding window. This leverages the BST's structure to avoid unnecessary computation.
The main challenge is balancing efficiency (not traversing more nodes than needed) with correctness (always finding the closest k
values, even if they're distributed across the tree).
target
.k
values from the sorted list, as these are the closest to the target
.Why this approach?
Sample Input:
target = 3.714286
k = 2
Result: [4, 3] (order does not matter)
The strategy is to traverse the BST, collect all values, and select the k
closest values to the target. This method is straightforward, leverages the BST's properties for traversal, and guarantees correctness. While more advanced approaches exist, this solution is easy to implement and understand, making it a solid choice for most use cases.