Python solution


  • 0
    A

    Simply go through the binary search tree. keep the closet value in the path until the end.

    def closestValue(self, root, target):
        ans = abs(target - root.val)
        ans_val = root.val
        
        while True:
            if abs(target - root.val) < ans:
                ans = abs(target - root.val)
                ans_val = root.val
    
            if root.right and target > root.val:
                root = root.right
            elif root.left and target < root.val:
                root = root.left
            else:
                break
        
        return ans_val

Log in to reply
 

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