def closestValue(self, root, target):
tmp = int(target + 0.5)
gap = abs(root.val  target)
ans = root
while root:
if tmp == root.val:
return root.val
elif tmp < root.val:
if abs(root.val  tmp) < gap:
gap = abs(root.val  tmp)
ans = root
root = root.left
else:
if abs(root.val  tmp) < gap:
gap = abs(root.val  tmp)
ans = root
root = root.right
return ans.val
Easy Understanding Python Iterative Solution


@StefanPochmann hahahahha, just change 2147483647 to 99999999999999, and it works again.. if you use larger number than 99999999999999, and it will be wrong again lol

@ruichang this code is the original version:
def closestValue(self, root, target): tmp = int(target + 0.5) while True: if tmp == root.val: return root.val elif tmp < root.val: if not root.left: return root.val root = root.left else: if not root.right: return root.val root = root.right

if you use larger number than 99999999999999
Good idea, let's use target=1e100, which is possible since it's a float :)
root = TreeNode(1) root.right = TreeNode(2) target = 1e100
You return 1 instead of 2.
I wonder how many solutions would correctly handle
target = float('inf')
. I suspect none. But that's a really mean case, and debatable whether it's valid.

@StefanPochmann yup, you are right, it's debatable, whatever I change it, you change the target to 1 googol, and I change the gap to 2 googol to conquer it > dead loop
So Thought is right, and others can learn something from this solution, that is enough. :)

@StefanPochmann if you choose target = 1e100, and your python solution will also return 1 instead of 2. So this is not the main problem. :)

class Solution(object): def closestValue(self, root, value): gap = abs(root.val  value) ans = root while root is not None: if root.val == value: return root.val elif value < root.val: if abs(root.val  value) < gap: ans = root gap = abs(root.val  value) root = root.left else: if abs(root.val  value) < gap: ans = root gap = abs(root.val  value) root = root.right return ans.val
why not use root.valval as inital value, which may not have bugs, stepahn : )