码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 270. Closest Binary Search Tree Value

时间:2017-01-04 07:51:18      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:close   elf   class   binary   span   get   float   __init__   init   

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.

沿着root向下找即可,每次判段一下是在root左边还是右边。注意没有child的情况。

 

 1 # Definition for a binary tree node.
 2 # class TreeNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution(object):
 9     def closestValue(self, root, target):
10         """
11         :type root: TreeNode
12         :type target: float
13         :rtype: int
14         """
15         #if target == root.val:
16         #    return root.val
17         
18         if target < root.val:
19             if not root.left:
20                 return root.val
21             else:
22                 c1 = self.closestValue(root.left, target)
23                 if abs(c1 - target) < abs(root.val - target):
24                     return c1
25                 else:
26                     return root.val
27         else:
28             if not root.right:
29                 return root.val
30             else:
31                 c2 = self.closestValue(root.right, target)
32                 if abs(c2 - target) < abs(root.val - target):
33                     return c2
34                 else:
35                     return root.val

 

Leetcode 270. Closest Binary Search Tree Value

标签:close   elf   class   binary   span   get   float   __init__   init   

原文地址:http://www.cnblogs.com/lettuan/p/6247221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!