Simple PYTHON - 55ms 90% O(logn)


  • 0
    V
    class Solution(object):
        def closestValue(self, root, target):
            """
            :type root: TreeNode
            :type target: float
            :rtype: int
            """
            if root == None:
                return float('inf')
            
            next = root.right
            if root.val > target:
                next = root.left
            
            nextVal = float('inf')
            if next:
                nextVal = self.closestValue(next, target)
            
            if abs(target - nextVal) < abs(target - root.val):
                return nextVal
            return root.val
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.