Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
根据题意,就是给你一个BST 的树形结构,给一个根节点作为着手点,往下找子节点。找到某个点的value和target的值最接近,输出那个值。
# 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 = abs(root.val - target)
ans = root
while root is not None:
if root.val == target:
return root.val
elif target < root.val:
if abs(root.val - target) < gap:
ans = root
gap = abs(root.val - target)
root = root.left
else:
if abs(root.val - target) < gap:
ans = root
gap = abs(root.val - target)
root = root.right
return ans.val
=========================
更快更简便的递归算法
class Solution(object):
def closestValue(self, root, target):
a = root.val
kid = root.left if target < a else root.right
if not kid: return a
b = self.closestValue(kid, target)
return min((b, a), key=lambda x: abs(target - x))
class Solution(object):
def closestValue(self, root, target):
path = []
while root:
path += root.val,
root = root.left if target < root.val else root.right
return min(path[::-1], key=lambda x: abs(target - x))