Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target. Example:
Input: root = [4,2,5,1,3], target = 3.714286
1 2 3 4 5
4 / \ 2 5 / \ 1 3
Output: 4
Solution DFS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# 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 classSolution: defclosestValue(self, root: Optional[TreeNode], target: float) -> int: ''' either in one of the left or right subtree ''' res, diff = root.val, float("inf") p = root while p: if abs(p.val - target) < diff: res = p.val diff = abs(p.val - target) p = p.left if target < p.val else p.right return res