边工作边刷题:70天一遍leetcode: day 82

Closest Binary Search Tree Value

要点:
https://repl.it/CfhL/1

# 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
        """
        gap = float("inf")
        closest = float("inf") # error: make use of dynamic type of a reference
        while root:
        	if gap>:
        		gap = abs(target-root.val)
        		closest = root
        	
        	if target<root.val:
        		root = root.left
        	else:
        		root = root.right
        return closest.val
        		
posted @ 2016-07-25 19:29  absolute100  阅读(93)  评论(0编辑  收藏  举报