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)
    

      

  • 相关阅读:
    CSUST--3.14排位周赛第四场 (全解)
    CSUST--3.7排位周赛第三场 (全解)
    android 代码功能测试junit test
    Sqlite数据库创建、删除、降级笔记
    三种进程和线程数据共享模块方法Queue》Pipe》manager
    多线程实例
    信号量
    红绿灯模型
    linshiwendang12--匈牙利
    spring--注入类型--构造方法(不常用)
  • 原文地址:https://www.cnblogs.com/lautsie/p/12267242.html
Copyright © 2011-2022 走看看