Simple Python solution based on Predecessor and Successor


  • 0
    class Solution(object):
        def closestValue(self, root, t):
            def close(root, t, pred, succ):
                if not root:
                    return
                if root.val == t:
                    pred[0] = succ[0] = root.val
                    return
                if t < root.val:
                    succ[0] = root.val
                    close(root.left, t, pred, succ)
                else:
                    pred[0] = root.val
                    close(root.right, t, pred, succ)
            
            pred, succ = [float('inf')], [float('inf')]
            close(root, t, pred, succ)
            pred, succ = pred[0], succ[0]
            return pred if abs(pred - t) <= abs(succ - t) or pred == succ else succ

Log in to reply
 

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