0272. Closest Binary Search Tree Value II

https://leetcode.com/problems/closest-binary-search-tree-value-ii

Description

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:

Example 2:

Constraints:

  • The number of nodes in the tree is n.

  • 1 <= k <= n <= 104.

  • 0 <= Node.val <= 109

  • -109 <= target <= 109

Follow up: Assume that the BST is balanced. Could you solve it in less than O(n) runtime (where n = total nodes)?

ac: iterative, 1 list + 1 stack

O(n) time key idea is in-order traversal of BST is incremental, make use of it.

ac2: recursive

maintain a k size window

Last updated

Was this helpful?