Grokking LinkedIn Coding Interview
Ask Author
Back to course home

0% completed

Vote For New Content
Closest Binary Search Tree Value II (hard)
On this page

Problem Statement

Examples

Try it yourself

Problem Statement

Given the root of a binary search tree, an integer target, and an integer k, return a 1D array total containing k values from the BST which are closest to the given target value. You may return the answer in any order.

Examples

  • Example 1:
    • Input: BST = [10,5,15,2,7,null,18], target = 8.5, k = 3
Image
  • Expected Output: [7,10,5]

  • Justification: The three numbers closest to 8.5 in the BST are 7, 10, and 5.

  • Example 2:

    • Input: BST = [20,10,30,5,15,null,null,3,8,null,17], target = 15.5, k = 2
Image
  • Expected Output: [15,17]

  • Justification: The two numbers closest to 15.5 in the BST are 15 and 17.

  • Example 3:

    • Input: BST = [4,2,6,1,3,5,7], target = 4.5, k = 1
Image
  • Expected Output: [4]
  • Justification: The number closest to 4.3 in the BST is 4.

Constraints:

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 10<sup>4</sup>
  • 0 <= Node.val <= 10<sup>9</sup>
  • -10<sup>9</sup> <= target <= 10<sup>9</sup>

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

On this page

Problem Statement

Examples

Try it yourself