File tree Expand file tree Collapse file tree 1 file changed +13
-6
lines changed
0270-closest-binary-search-tree-value Expand file tree Collapse file tree 1 file changed +13
-6
lines changed Original file line number Diff line number Diff line change 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+
914class 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
You can’t perform that action at this time.
0 commit comments