BST

LeetCode 270 Closest Binary Search Tree Value (Python)

Posted by 小明MaxMing on August 8, 2020

题目

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.

解题思路

从根开始和目标值进行比较,如果目标值小于当前节点,向左遍历,否则向右遍历

代码

class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        res = root.val
        while root:
            res = min(res, root.val, key = lambda x: abs(target - x))
            root = root.left if target < root.val else root.right
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅