*270. Closest Binary Search Tree Value

https://leetcode.com/problems/closest-binary-search-tree-value/

solution

class Solution:
    def closestValue(self, root, target):
        upper = root
        lower = root

        while root:
            if root.val > target:
                upper = root  # 先记录再往后迭代
                root = root.left
            elif root.val < target:
                lower = root
                root = root.right
            else:
                return root.val

        if abs(upper.val - target) > abs(lower.val - target):
            return lower.val
        return upper.val

时间复杂度:O(h) 空间复杂度:O(h)

dfs

follow up

272. Closest Binary Search Tree Value II

Last updated