Closest Binary Search Tree Value

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

这是一道比较简单的题目,其实就是利用在BST中查找一个给定元素的思路,一路逼近和查找,代码如下:

# 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
        """
        closet = root.val
        cur = root
        while cur:
            if abs(target - cur.val) < abs(target - closet):
                closet = cur.val
            if cur.val > target:
                cur = cur.left
            else:
                cur = cur.right
        return closet
原文地址:https://www.cnblogs.com/sherylwang/p/5668270.html