FastPrepKth Closest Element in a BST

Kth Closest Element in a BST

LinkedIn logoLinkedIn● MediumFULLTIMEONSITE INTERVIEW

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) → int

Examples

Example 1

root = [4,2,5,1,3]target = 3k = 3return = 4

The 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 = 2

Values 2 and 4 are both distance 1 from 3. The smaller value 2 comes first.

Constraints

  • root is 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 1 and 10000 nodes.
  • The level-order serialization has at most 19999 entries, including null missing-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.

More LinkedIn problems

See LinkedIn hiring insights
Saved
public int kthClosest(TreeNode root, int target, int k) {
    // write your code here
}
root[4,2,5,1,3]
target3
k3
expected4
Checking account…