Closest Binary Search Tree Value II Problem
Description
LeetCode Problem 272.
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:
- The number of nodes in the tree is
n. 1 <= k <= n <= 10^4.0 <= Node.val <= 10^9-10^9 <= target <= 10^9
Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?
Solution
Approach: In-Order Traversal with a Sliding Window
An in-order traversal of a BST visits the values in increasing order. In a sorted list, the k values closest to target are always k consecutive values: if a value is in the answer, every value between it and target is even closer.
So we keep a window of the last k values seen during the traversal (a deque) and look at each new value v, which is larger than everything in the window:
- While the window has fewer than
kvalues, addv. - If
vis closer totargetthan the window's smallest valuewindow[0], the window should move right: dropwindow[0]and addv. - Otherwise stop.
vis no closer thanwindow[0], sovis already pasttarget, and every later value is larger and farther still.
The early stop is what makes this faster than collecting all values: the traversal ends soon after it passes target. We use an iterative in-order traversal with a stack, so a very deep tree does not overflow the call stack.
Complexity: O(n) time in the worst case, but the traversal stops soon after it passes target. O(h + k) space for the stack and the window, where h is the height of the tree.
import collections
class Solution:
def closestKValues(self, root: Optional[TreeNode], target: float, k: int) -> List[int]:
window = collections.deque() # k consecutive values of the in-order (sorted) sequence
stack, node = [], root
while stack or node:
while node: # go as far left as possible
stack.append(node)
node = node.left
node = stack.pop() # the next value in increasing order
if len(window) < k:
window.append(node.val)
elif abs(node.val - target) < abs(window[0] - target):
window.popleft() # slide the window one value to the right
window.append(node.val)
else:
break # this value and every larger one are farther than the window's values
node = node.right
return list(window)