File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ #!/usr/bin/python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ # Author: Wei Dai
5
+
6
+ # ****************
7
+ # Descrption:
8
+ # 270. Closest Binary Search Tree Value
9
+
10
+ #Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
11
+ # ****************
12
+
13
+ # 思路:
14
+ # BST上二分搜索 把partial optimal和root自己的值进行比较取最优
15
+
16
+ # ****************
17
+ # Final Solution *
18
+ # ****************
19
+ class Solution (object ):
20
+ def closestValue (self , root , target ):
21
+ """
22
+ :type root: TreeNode
23
+ :type target: float
24
+ :rtype: int
25
+ """
26
+ if not root :
27
+ return - 1
28
+ if not root .left and not root .right :
29
+ return root .val
30
+
31
+ cur = root .val
32
+ if target > cur :
33
+ halfOpt = self .closestValue (root .right , target )
34
+ else :
35
+ halfOpt = self .closestValue (root .left , target )
36
+ cDif , hDif = abs (cur - target ), abs (halfOpt - target )
37
+ res = cur if cDif < hDif else halfOpt
38
+ return res
You can’t perform that action at this time.
0 commit comments