8/18
It can be equal when looking for them.
Python
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
lowerVal = self.findLower(root, target)
upperVal = self.findUpper(root, target)
print(lowerVal)
print(upperVal)
if not (lowerVal == None) and not (upperVal == None):
if abs(target-lowerVal) > abs(upperVal - target):
return upperVal
else:
return lowerVal
if lowerVal:
return lowerVal
if upperVal:
return upperVal
return None
def findLower(self, root, target):
lowerVal = None
while root:
if target >= root.val:
lowerVal = root.val
root = root.right
else:
root = root.left
return lowerVal
def findUpper(self, root, target):
upperVal = None
while root:
if target <= root.val:
upperVal = root.val
root = root.left
else:
root = root.right
return upperVal