首页 > 其他 > 详细

Closest Binary Search Tree Value

时间:2016-07-14 01:52:38      阅读:153      评论:0      收藏:0      [点我收藏+]

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

这是一道比较简单的题目,其实就是利用在BST中查找一个给定元素的思路,一路逼近和查找,代码如下:

# 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
        """
        closet = root.val
        cur = root
        while cur:
            if abs(target - cur.val) < abs(target - closet):
                closet = cur.val
            if cur.val > target:
                cur = cur.left
            else:
                cur = cur.right
        return closet

 

Closest Binary Search Tree Value

原文:http://www.cnblogs.com/sherylwang/p/5668270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!