Kth Closest Element in a BST
Problem statement
Given the root of a binary search tree, an integer target, and a one-based rank k, return the value of the kth closest node to target.
Order nodes by the absolute distance |node.val - target|. If two values have the same distance, the smaller value comes first. All node values are distinct, and k is a valid rank.
Function
kthClosest(root: TreeNode, target: int, k: int) → intExamples
Example 1
root = [4,2,5,1,3]target = 3k = 3return = 4The values ordered by distance and then by value are [3,2,4,1,5]. The third value is 4.
Example 2
root = [4,2,6]target = 3k = 1return = 2Values 2 and 4 are both distance 1 from 3. The smaller value 2 comes first.
Constraints
rootis a nonempty binary search tree with distinct integer keys. Every left-subtree key is smaller than its parent, and every right-subtree key is larger.- The tree has between
1and10000nodes. - The level-order serialization has at most
19999entries, includingnullmissing-child markers. -1000000 <= node.val <= 1000000.-1000000 <= target <= 1000000.1 <= k <= number of nodes.
Source note: Source images are source-neutral excerpts of author-reported interview prompts.