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

时间:2023-03-09 06:53:20
边工作边刷题: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