Skip to main content
LeetCode 272, Hard. Topics: Stack, Tree, Depth-First Search, Binary Search Tree, Two Pointers, Binary Tree, Heap (Priority Queue). View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

Problem

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. Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?

Examples

Example 1

Constraints

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

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026