-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathbst_closest_value.py
More file actions
29 lines (24 loc) · 741 Bytes
/
Copy pathbst_closest_value.py
File metadata and controls
29 lines (24 loc) · 741 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def closest_value(root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
a = root.val
kid = root.left if target < a else root.right
if not kid:
return a
b = closest_value(kid, target)
return min((a, b), key=lambda x: abs(target - x))