#270
Easy Algorithms Closest binary search tree value
Binary Search Tree Depth-First Search Binary Search Tree Binary Tree
49.2% acceptance
Mar 31, 2026
1902
166
Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.
Solution
Rust
Time O(n)
Space O(1)
// 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_value(root: Option<Rc<RefCell<TreeNode>>>, target: f64) -> i32 {
let mut closest = root.as_ref().unwrap().borrow().val;
let mut node = root;
while let Some(n) = node {
let n_ref = n.borrow();
let val = n_ref.val;
if (val as f64 - target).abs() < (closest as f64 - target).abs()
|| ((val as f64 - target).abs() == (closest as f64 - target).abs() && val < closest)
{
closest = val;
}
node = if target < val as f64 {
n_ref.left.clone()
} else {
n_ref.right.clone()
};
}
closest
}
}