Skip to content

Closest Value in BST

LeetCode

01 · Question

Find the value in a BST that is closest to the target.

02 · Solution

Reference solution

1def closestValue(root: Optional[TreeNode], target: float) -> int:
2 closest = root.val
3 cur = root
4 while cur:
5 if abs(cur.val - target) < abs(closest - target):
6 closest = cur.val
7 cur = cur.left if target < cur.val else cur.right
8 return closest