LeetCode-Python-270. 最接近的二叉搜索树值

给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。

注意:

  • 给定的目标值 target 是一个浮点数
  • 题目保证在该二叉搜索树中只会存在一个最接近目标值的数

示例:

输入: root = [4,2,5,1,3],目标值 target = 3.714286

    4
   / \
  2   5
 / \
1   3

输出: 4

思路:

中序遍历然后在得到的数组里找最接近的数。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        def inorder(node):
            if not node:
                return []
            return inorder(node.left) + [node.val] + inorder(node.right)
        nums = inorder(root)
        res = root.val
        minum = 2 ** 32
        # print nums
        for i, x in enumerate(nums):
            distance = abs(target - x)
            print distance, minum, res
            if distance < minum:
                res = x
                minum = distance
        return res

下面的写于2019年08月29日14:04:24 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def closestValue(self, root, target):
        """
        :type root: TreeNode
        :type target: float
        :rtype: int
        """
        
        def inOrder(node):
            if not node:
                return []
            return inOrder(node.left) + [node.val] + inOrder(node.right)
        
        l = inOrder(root)
        res = 0
        min_sub = float("inf")
        
        for num in l:
            if abs(num - target) < min_sub:
                min_sub = abs(num - target)
                res = num
        return res

 


版权声明:本文为qq_32424059原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。