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)
    

      

  • 相关阅读:
    Robot Framework-取出接口返回的字段
    利用VBA宏批量解决Word中图片大小、居中设置
    封装和继承
    Shiro的学习
    Redis集群搭建
    Mysql主从架构
    idea修改maven的默认配置不生效
    Mybatis笔记
    【python】文件的读写方法(r;r+;rb;w;w+;wb;a;a+;ab)
    【Python】Xpath语法&示例
  • 原文地址:https://www.cnblogs.com/lautsie/p/12267242.html
Copyright © 2011-2022 走看看