270 Closest Binary Search Tree Value
Python
class Solution(object):
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
if root.left is None and root.right is None:
return root.val
d = root.val - target
if d > 0:
if root.left:
if abs(d) < abs(self.closestValue(root.left,target)-target):
return root.val
else:
return self.closestValue(root.left,target)
return root.val
if d < 0:
if root.right:
if abs(d) < abs(self.closestValue(root.right,target)-target):
return root.val
else:
return self.closestValue(root.right,target)
return root.val
if d == 0:
return root.val