Closest BST Values II

Given a BST, output the k closest values in this BST to x. Sort the output by value.

The output set is guaranteed to be unique.

Do not convert the BST to a list.


  • bst: a valid BST of size n.
  • x: an integer representing the number to find the k closest numbers to.
  • k: an integer.


A list of integers containing the k closest numbers to x.


Example 1:


1bst = <See explanation>
2x = 7
3k = 4

Output: [5, 6, 8, 10]


All four numbers in the output are within 3 away from 7.


  • 1 <= k <= n <= 10^5

Try it yourself




Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Contrary to popular belief, Lorem Ipsum is not simply random text.

1  >>> a = [1, 2, 3]
2  >>> a[-1]
3  3

Get premium for instant access to all content and solutions