> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Closest Binary Search Tree Value II

> Tested Python solution for LeetCode 272 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 272, [Hard](/catalog/hard). Topics: [Stack](/catalog/topics/stack), [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Search Tree](/catalog/topics/binary-search-tree), [Two Pointers](/catalog/topics/two-pointers), [Binary Tree](/catalog/topics/binary-tree), [Heap (Priority Queue)](/catalog/topics/heap-priority-queue). [View on LeetCode](https://leetcode.com/problems/closest-bst-value-ii/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 272   # by problem number
lcpy gen -s closest_bst_value_ii   # by problem name
```

## 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](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0272.Closest%20Binary%20Search%20Tree%20Value%20II/images/closest1-1-tree.jpg)

```
Input: root = [4,2,5,1,3], target = 3.714286, k = 2
Output: [4,3]
```

```
Input: root = [1], target = 0.000000, k = 1
Output: [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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/closest_bst_value_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/closest_bst_value_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq

from leetcode_py import TreeNode


class Solution:
    # Time: O(n log k) where n is the node count
    # Space: O(h + k)
    def closest_k_values(self, root: TreeNode[int], target: float, k: int) -> list[int]:
        heap: list[tuple[float, int]] = []
        stack: list[TreeNode[int]] = []
        node: TreeNode[int] | None = root
        while stack or node is not None:
            while node is not None:
                stack.append(node)
                node = node.left
            node = stack.pop()
            diff = abs(node.val - target)
            if len(heap) < k:
                heapq.heappush(heap, (-diff, node.val))
            elif -heap[0][0] > diff:
                heapq.heapreplace(heap, (-diff, node.val))
            node = node.right
        return [val for _, val in heap]
```

## Complexity

| Time | Space |
| - | - |
| O(n log k) where n is the node count | O(h + k) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.