270. Closest Binary Search Tree Value - cocoder39/coco39_LC GitHub Wiki
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
res = root.val
while root:
if abs(res - target) > abs(root.val - target):
res = root.val
elif abs(res - target) == abs(root.val - target):
res = min(res, root.val)
if root.val > target:
root = root.left
else:
root = root.right
return res
===========================================
int closestValue(TreeNode* root, double target) {
int res = root->val;
while (root) {
res = abs(root->val - target) > abs(res - target) ? res : root->val;
root = root->val > target ? root->left : root->right;
}
return res;
}