Skip to content

Commit c802b61

Browse files
committed
Sync LeetCode submission Runtime - 1 ms (20.77%), Memory - 19.5 MB (63.53%)
1 parent 2f4bff8 commit c802b61

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed
Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
1-
# Approach 1 - Recursive Inorder + Linear search, O(N) time
1+
# Approach 3: Binary Search
2+
3+
# h = height of the tree
4+
# Time: O(h)
5+
# Space: O(1)
26

37
# Definition for a binary tree node.
48
# class TreeNode:
59
# def __init__(self, val=0, left=None, right=None):
610
# self.val = val
711
# self.left = left
812
# self.right = right
13+
914
class Solution:
1015
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
11-
12-
def inorder(r: TreeNode):
13-
return inorder(r.left) + [r.val] + inorder(r.right) if r else []
14-
15-
return min(inorder(root), key=lambda x: abs(x-target))
16+
closest = root.val
17+
18+
while root:
19+
closest = min(root.val, closest, key = lambda x: (abs(target - x), x))
20+
root = root.left if target < root.val else root.right
21+
22+
return closest
1623

0 commit comments

Comments
 (0)