【Lintcode】python - [900] Closest Binary Search Tree Value 個人解法筆記

題目出處

900 · Closest Binary Search Tree Value

難度

easy

個人範例程式碼

from lintcode import (
    TreeNode,
)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the given BST
    @param target: the given target
    @return: the value in the BST that is closest to the target
    """
    def closest_value(self, root: TreeNode, target: float) -> int:
        # write your code here
        if not root:
            return -1

        upper = float("inf")
        lower = float("-inf") 

        stack = collections.deque([root])
        while stack:
            node = stack.pop()
            if node.val > target:
                upper = min(node.val, upper)
                if node.left:
                    stack.append(node.left)
            elif node.val < target:
                lower = max(node.val, lower)
                if node.right:
                    stack.append(node.right)
            else: # same value
                return node.val

        return upper if (upper - target < target - lower) else lower

算法說明

算是考 BST 的基本定義,這邊可以用圖來說明一下發生的現象。

由圖上我們可以發現隨著搜尋過程中,target 區間正在不斷的縮小,此題就是利用這個特性。

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

input handling

root 沒東西時,回傳 -1

Boundary conditions

搜尋到沒有東西,或是搜尋到「等於 target (必定為最近)」,直接 return 了

Reference