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)
    

      

  • 相关阅读:
    CAN器件
    团队赋能
    电子模拟开关
    名言出处
    危机管理
    隔离技术
    让CSS布局更加直观:box-sizing
    浅谈跨域以WebService对跨域的支持
    给初学者的20个CSS实用建议
    JS中eval处理JSON数据 为什么要加括号
  • 原文地址:https://www.cnblogs.com/lautsie/p/12267242.html
Copyright © 2011-2022 走看看