19. K Closest Values
β GFG solution to the K Closest Values in BST problem: find k values closest to target using iterative inorder traversal and two-pointer technique. π
π§© Problem Description
π Examples
Example 1
Input: root = [20, 8, 22, 4, 12, N, N, N, N, 10, 14], target = 17, k = 3
Output: [14, 20, 12]
Explanation: Absolute difference of 17 with 14 and 20 is 3 each, but we choose
the smaller value (14) first. Then 12 and 22 both have absolute difference 5,
so we choose the smaller value (12).Example 2
Input: root = [5, 4, 8, 1], target = 5, k = 2
Output: [5, 4]
Explanation: The absolute difference of 5 with itself is 0, and with 4 is 1.π Constraints
β
My Approach
Iterative Inorder + Binary Search + Two Pointers
π Time and Auxiliary Space Complexity
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
πVisitor Count
Last updated