[leetcode]Closest Binary Search Tree Value

Posted 阿牧遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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)

  

以上是关于[leetcode]Closest Binary Search Tree Value的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 270: Closest Binary Search Tree Value

[leetcode]Closest Binary Search Tree Value

[LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值

Leetcode 743. Closest Leaf in a Binary Tree

LeetCode-Closest Binary Search Tree Value II

[LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二