Skip to main content

Closest Binary Search Tree Value

Problem Statement

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Example 1:

Input: root = {5,4,9,2,#,8,10} and target = 6.124780
Output: 5
Explanation:
Binary tree {5,4,9,2,#,8,10}, denote the following structure:
5
/ \
4 9
/ / \
2 8 10

Example 2:

Input: root = {3,2,4,1} and target = 4.142857
Output: 4
Explanation:
Binary tree {3,2,4,1}, denote the following structure:
3
/ \
2 4
/
1

Code

Python
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""

class Solution:
"""
@param root: the given BST
@param target: the given target
@return: the value in the BST that is closest to the target
"""
def closestValue(self, root, target):
upper = root
lower = root
while root:
if target > root.val:
lower = root
root = root.right
elif target < root.val:
upper = root
root = root.left
else:
return root.val
if abs(upper.val - target) <= abs(lower.val - target):
return upper.val
return lower.val