Closest Value in BST

LeetCode

LeetCode: https://leetcode.com/problems/closest-binary-search-tree-value/

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

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
4
0
2
1
5
2
1
3
3
4
tree=[4, 2, 5, 1, 3]
target=3.7
closest=4
Step 1 / 3
Step 1:
Walk down the BST, updating the closest value.
Focus: select @ [0]
target=3.7closest=4