Skip to content

Latest commit

 

History

History
45 lines (41 loc) · 1.25 KB

270. Closest Binary Search Tree Value.md

File metadata and controls

45 lines (41 loc) · 1.25 KB

8/18

270. Closest Binary Search Tree Value

Using Find Predecessor and Successor

It can be equal when looking for them.

Python

class Solution:
    def closestValue(self, root: Optional[TreeNode], target: float) -> int:
        lowerVal = self.findLower(root, target)
        upperVal = self.findUpper(root, target)
        print(lowerVal)
        print(upperVal)
        if not (lowerVal == None) and not (upperVal == None):
            if abs(target-lowerVal) > abs(upperVal - target):
                return upperVal
            else:
                return lowerVal
        if lowerVal:
            return lowerVal
        if upperVal:
            return upperVal
        return None
    
    def findLower(self, root, target):
        lowerVal = None
        while root:
            if target >= root.val:
                lowerVal = root.val
                root = root.right
            else:
                root = root.left 
        return lowerVal
                
    def findUpper(self, root, target):
        upperVal = None
        while root:
            if target <= root.val:
                upperVal = root.val
                root = root.left
            else:
                root = root.right
                
        return upperVal