270. Closest Binary Search Tree Value
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the integer value in a Binary Search Tree (BST) that is closest to a given floating-point target. A key property of a BST is that for any node, all values in its left subtree are smaller, and all values in its right subtree are larger. We need to leverage this property for an efficient solution. An additional requirement is to return the smaller value in case of a tie in closeness.
Solution
Closest Binary Search Tree Value in Python
# 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 closestValue(self, root: Optional[TreeNode], target: float) -> int:
# Initialize 'closest' with the root's value.
# Constraints guarantee the tree is not empty.
closest = root.val
node = root
# Traverse the tree. The path is determined by the target value.
while node:
# Check if the current node's value is a better candidate.
# A candidate is better if it's strictly closer, or
# if it's equally close but has a smaller value.
if abs(node.val - target) < abs(closest - target):
closest = node.val
elif abs(node.val - target) == abs(closest - target):
closest = min(closest, node.val)
# Navigate the tree using the BST property to find the path
# that would lead to the target value.
if target < node.val:
node = node.left
elif target > node.val:
node = node.right
else: # target == node.val
# If we find an exact match, the difference is 0, which is the minimum possible.
return node.val
# After the loop, 'closest' holds the value of the node closest to the target.
return closest
Closest Binary Search Tree Value in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
// Initialize 'closest' with the root's value.
// Constraints guarantee the tree is not empty.
int closest = root.val;
TreeNode node = root;
// Traverse the tree. The path is determined by the target value.
while (node != null) {
// Check if the current node's value is a better candidate.
// A candidate is better if it's strictly closer, or
// if it's equally close but has a smaller value.
if (Math.abs(node.val - target) < Math.abs(closest - target)) {
closest = node.val;
} else if (Math.abs(node.val - target) == Math.abs(closest - target)) {
closest = Math.min(closest, node.val);
}
// Navigate the tree using the BST property to find the path
// that would lead to the target value.
if (target < node.val) {
node = node.left;
} else if (target > node.val) {
node = node.right;
} else { // target == node.val
// If we find an exact match, the difference is 0, which is the minimum possible.
return node.val;
}
}
// After the loop, 'closest' holds the value of the node closest to the target.
return closest;
}
}
Closest Binary Search Tree Value in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode* root, double target) {
// Initialize 'closest' with the root's value.
// Constraints guarantee the tree is not empty.
int closest = root->val;
TreeNode* node = root;
// Traverse the tree. The path is determined by the target value.
while (node != nullptr) {
// Check if the current node's value is a better candidate.
// A candidate is better if it's strictly closer, or
// if it's equally close but has a smaller value.
if (std::abs(node->val - target) < std::abs(closest - target)) {
closest = node->val;
} else if (std::abs(node->val - target) == std::abs(closest - target)) {
closest = std::min(closest, node->val);
}
// Navigate the tree using the BST property to find the path
// that would lead to the target value.
if (target < node->val) {
node = node->left;
} else if (target > node->val) {
node = node->right;
} else { // target == node->val
// If we find an exact match, the difference is 0, which is the minimum possible.
return node->val;
}
}
// After the loop, 'closest' holds the value of the node closest to the target.
return closest;
}
};
Closest Binary Search Tree Value in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function closestValue(root: TreeNode | null, target: number): number {
// Initialize 'closest' with the root's value.
// Constraints guarantee the tree is not empty, so root is not null.
// The '!' non-null assertion operator tells TypeScript that root is not null here.
let closest: number = root!.val;
let node: TreeNode | null = root;
// Traverse the tree. The path is determined by the target value.
while (node !== null) {
// Check if the current node's value is a better candidate.
// A candidate is better if it's strictly closer, or
// if it's equally close but has a smaller value.
if (Math.abs(node.val - target) < Math.abs(closest - target)) {
closest = node.val;
} else if (Math.abs(node.val - target) === Math.abs(closest - target)) {
closest = Math.min(closest, node.val);
}
// Navigate the tree using the BST property to find the path
// that would lead to the target value.
if (target < node.val) {
node = node.left;
} else if (target > node.val) {
node = node.right;
} else { // target === node.val
// If we find an exact match, the difference is 0, which is the minimum possible.
return node.val;
}
}
// After the loop, 'closest' holds the value of the node closest to the target.
return closest;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.