zoukankan      html  css  js  c++  java
  • [leetcode]Closest Binary Search Tree Value

    找BST里最近的值,用两次logn的搜索。注意递归过程中记录遇到过的closest。

    看了题解可以不用递归,而且一次搜索中完成。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def closestValue(self, root: TreeNode, target: float) -> int:
            smaller = self.closestSmallerValue(root, target, None)
            bigger = self.closestBiggerValue(root, target, None)
            if smaller is None:
                return bigger
            if bigger is None:
                return smaller
            if smaller is None and bigger is None:
                return None
            
            if abs(target - smaller) < abs(target - bigger):
                return smaller
            else:
                return bigger
            
            
        def closestSmallerValue(self, root, target, current):
            if root.val == target:
                return root.val
            if root.val > target:
                if root.left is None:
                    return current
                else:
                    return self.closestSmallerValue(root.left, target, current)
            if root.val < target:
                if root.right is None:
                    return root.val
                else:
                    return self.closestSmallerValue(root.right, target, root.val)
        
        def closestBiggerValue(self, root, target, current):
            if root.val == target:
                return root.val
            if root.val < target:
                if root.right is None:
                    return current
                else:
                    return self.closestBiggerValue(root.right, target, current)
            if root.val > target:
                if root.left is None:
                    return root.val
                else:
                    return self.closestBiggerValue(root.left, target, root.val)
    

      

  • 相关阅读:
    内存碎片
    内核对象之异步IO请求完成时调用一个函数
    线程池之在内核对象触发时调用一个对象
    线程池之每隔一段时间调用一个函数
    线程池
    logging模块
    装饰器
    django 2.0 url匹配
    django models 文件夹
    转载
  • 原文地址:https://www.cnblogs.com/lautsie/p/12267242.html
Copyright © 2011-2022 走看看