BST二叉树的二分查找

900. 二叉搜索树中最接近的值

中文
English

给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值

样例

样例1

输入: root = {5,4,9,2,#,8,10} and target = 6.124780
输出: 5
解释:
二叉树 {5,4,9,2,#,8,10},表示如下的树结构:
        5
       / \
     4    9
    /    / \
   2    8  10

样例2

输入: root = {3,2,4,1} and target = 4.142857
输出: 4
解释:
二叉树 {3,2,4,1},表示如下的树结构:
     3
    / \
  2    4
 /
1

注意事项

  • 给出的目标值为浮点数
  • 我们可以保证只有唯一一个最接近给定值的节点

 

"""
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 closestValue(self, root, target):
        # write your code here
        """
        特别简单好理解的方法,非递归:
如果当前root值比target大,就暂且把这个root值当成上限,然后往左边走
如果当前root值比target小,就暂且把这个root值当成下限,然后往右边走
左右摇摆着走,知道发现两个最接近target的值,由于是inplace的更新上下限,而且不递归,所以没有额外的空间损耗
O(h) time and O(1) space
        """
        if not root:
            return None
        
        lower, upper = root, root
        node = root
        while node:
            if node.val < target:
                lower = node
                node = node.right
            elif node.val > target:
                upper = node
                node = node.left
            else:
                return node.val
        return lower.val if abs(upper.val-target) > abs(lower.val-target) else \
            upper.val
        

 

posted @ 2019-10-05 12:13  bonelee  阅读(414)  评论(0编辑  收藏  举报