LeetCode 270. Closest Binary Search Tree Value

Description

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

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

Example 1:

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

Example 2:

Input: root = [1], target = 4.428571
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 109
  • -109 <= target <= 109

Explanation

Base on the characteristics of binary search tree to search for the target.

Python Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        self.closest = None
        
        self.search(root, target)
        
        return self.closest.val
        
    def search(self, root, target):
        if not root:
            return
        
        if not self.closest or abs(root.val - target) < abs(self.closest.val - target):
            self.closest = root
        
        if target < root.val:
            self.search(root.left, target)        
        elif target > root.val:
            self.search(root.right, target)
        
  • Time Complexity: O(log(N)).
  • Space Complexity: O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *