Skip to content

Commit a0178ba

Browse files
author
Wei Dai
committed
tree
1 parent 674c36a commit a0178ba

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

tree/closestBinarySearchTreeValue.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

0 commit comments

Comments
 (0)