-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy path270.py
More file actions
27 lines (26 loc) · 758 Bytes
/
270.py
File metadata and controls
27 lines (26 loc) · 758 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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def closestValue(self, root, target):
"""
:type root: TreeNode
:type target: float
:rtype: int
"""
res, d = [0], [float("inf")]
def dfs(node):
if node:
new = node.val - target if node.val >= target else target - node.val
if new < d[0]:
d[0] = new
res[0] = node.val
if target < node.val:
dfs(node.left)
else:
dfs(node.right)
dfs(root)
return res[0]