Problem 446391 · hard · Phase 04 Non-Linear Data Structures

The k Stored Values Nearest a Target

binary search tree · inorder traversal · two pointers

A radio stores its preset frequencies in a binary search tree with distinct integer values. Given a target and an integer k (1 <= k <= number of nodes), return the k stored values closest to target, sorted ascending. When two candidates are equally distant, the smaller one is preferred.

Examples

       20
      /  \
    10    30
   / \   /  \
  5  15 25  40

Input:  root = build_tree([20, 10, 30, 5, 15, 25, 40]), target = 18, k = 3
Output: [15, 20, 25]

Input:  root = build_tree([20, 10, 30, 5, 15, 25, 40]), target = 20, k = 2
Output: [15, 20]        (15 and 25 are both 5 away; 15 wins)

Constraints

  • 1 <= k <= number of nodes <= 3000
  • All values are distinct integers
  • Target O(n) time or better

Goals

  • Exploit the sorted inorder sequence
  • Grow a window outward from the target position
  • Break distance ties deterministically
Starting Python…