#272
Hard Algorithms Closest binary search tree value ii
Two Pointers Stack Tree Depth-First Search Binary Search Tree Heap (Priority Queue) Binary Tree
61.2% acceptance
Mar 31, 2026
1343
51
Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Solution
Rust
Time O(n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn closest_k_values(root: Option<Rc<RefCell<TreeNode>>>, target: f64, k: i32) -> Vec<i32> {
use std::collections::VecDeque;
let mut deque: VecDeque<i32> = VecDeque::new();
Self::inorder(&root, target, k as usize, &mut deque);
deque.into_iter().collect()
}
fn inorder(node: &Option<Rc<RefCell<TreeNode>>>, target: f64, k: usize, deque: &mut std::collections::VecDeque<i32>) {
if let Some(n) = node {
let n_ref = n.borrow();
Self::inorder(&n_ref.left, target, k, deque);
if deque.len() < k {
deque.push_back(n_ref.val);
} else if (n_ref.val as f64 - target).abs() < (*deque.front().unwrap() as f64 - target).abs() {
deque.pop_front();
deque.push_back(n_ref.val);
} else {
return;
}
Self::inorder(&n_ref.right, target, k, deque);
}
}
}