Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286, k = 2
Output: [4,3]Example 2:
Input: root = [1], target = 0.000000, k = 1
Output: [1]Constraints:
n.1 <= k <= n <= 10⁴.0 <= Node.val <= 10⁹-10⁹ <= target <= 10⁹Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(node, arr):
if not node:
return
arr.append(node.val)
dfs(node.left, arr)
dfs(node.right, arr)
arr = []
dfs(root, arr)
arr.sort(key = lambda x: (abs(x - target), x))
return arr[:k]Where is the number of nodes in the tree
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(node, heap):
if not node:
return
if len(heap) < k:
heappush(heap, (-abs(node.val - target), node.val))
else:
if abs(node.val - target) <= abs(heap[0][0]):
heappop(heap)
heappush(heap, (-abs(node.val - target), node.val))
dfs(node.left, heap)
dfs(node.right, heap)
heap = []
dfs(root, heap)
return [x[1] for x in heap]Where is the number of nodes in the tree and is the size of our heap
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(node, arr):
if not node:
return
dfs(node.left, arr)
arr.append(node.val)
dfs(node.right, arr)
arr = []
dfs(root, arr)
left = bisect_left(arr, target) - 1
right = left + 1
ans = []
while len(ans) < k:
if right == len(arr) or abs(arr[left] - target) <= abs(arr[right] - target):
ans.append(arr[left])
left -= 1
else:
ans.append(arr[right])
right += 1
return ansWhere is the number of nodes in the tree and is the size of our sliding window
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(node, arr):
if not node:
return
dfs(node.left, arr)
arr.append(node.val)
dfs(node.right, arr)
arr = []
dfs(root, arr)
left = 0
right = len(arr) - k
while left < right:
mid = (left + right) // 2
if abs(target - arr[mid + k]) < abs(target - arr[mid]):
left = mid + 1
else:
right = mid
return arr[left:left + k]Where is the number of nodes in the tree and is the number of closest values to return
class Solution:
def closestKValues(self, root: TreeNode, target: float, k: int) -> List[int]:
def dfs(node, queue):
if not node:
return
dfs(node.left, queue)
queue.append(node.val)
if len(queue) > k:
if (abs(target - queue[0]) <= abs(target - queue[-1])):
queue.pop()
return
else:
queue.popleft()
dfs(node.right, queue)
queue = deque()
dfs(root, queue)
return list(queue)Where is the number of nodes in the tree and is the number of closest values to return