@@ -23,24 +23,28 @@ def insert(self, val):
23
23
24
24
25
25
class Solution (object ):
26
-
27
26
def closestValue (self , root , target ):
27
+ """
28
+ :type root: TreeNode
29
+ :type target: float
30
+ :rtype: int
31
+ """
28
32
return self .closestValueHelper (root , target , float ("inf" ))
29
33
30
- def closestValueHelper (self , root , target , closest ):
34
+ def closestValueHelper (self , root , targetVal , currentClosestNodeVal ):
31
35
currentNode = root
32
36
while currentNode is not None :
33
- t1 = abs (target - closest )
34
- t2 = abs (currentNode .val - target )
35
- if t1 > t2 :
36
- closest = currentNode .val
37
- if target < currentNode .val :
37
+ currentClosestDiff = abs (targetVal - currentClosestNodeVal )
38
+ currentDiff = abs (currentNode .val - targetVal )
39
+ if currentClosestDiff > currentDiff :
40
+ currentClosestNodeVal = currentNode .val
41
+ if targetVal < currentNode .val :
38
42
currentNode = currentNode .left
39
- elif target > currentNode .val :
43
+ elif targetVal > currentNode .val :
40
44
currentNode = currentNode .right
41
45
else :
42
46
break
43
- return closest
47
+ return currentClosestNodeVal
44
48
45
49
46
50
test_tree = TreeNode (4 ).insert (2 ).insert (5 ).insert (1 ).insert (3 )
0 commit comments