270 Closest Binary Search Tree Value

Python

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):

    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        if root.left is None and root.right is None:
            return root.val
        d = root.val - target
        if d > 0:
            if root.left:
                if abs(d) < abs(self.closestValue(root.left,target)-target):
                    return root.val
                else:
                    return self.closestValue(root.left,target)
            return root.val
        if d < 0:
            if root.right:
                if abs(d) < abs(self.closestValue(root.right,target)-target):
                    return root.val
                else:
                    return self.closestValue(root.right,target)
            return root.val
        if d == 0:
            return root.val

results matching ""

    No results matching ""