-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0270-closest-binary-search-tree-value.py
More file actions
45 lines (36 loc) · 1.08 KB
/
0270-closest-binary-search-tree-value.py
File metadata and controls
45 lines (36 loc) · 1.08 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
result = root.val
minDis = abs(root.val - target)
def traverse(node):
nonlocal result
nonlocal minDis
if not node:
return
currDis = abs(node.val - target)
if currDis == minDis:
result = min(result, node.val)
if currDis < minDis:
minDis = currDis
result = node.val
if node.left:
traverse(node.left)
if node.right:
traverse(node.right)
traverse(root)
return result
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(5)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)
target = 3.714268
print(Solution().closestValue(root, target))