Closest Neighbour in BST

easy

Given the root of a binary search tree and an integer key, return the value in the BST that is closest to key — the one with the smallest absolute difference |value - key|. If two values tie, return the smaller one.

The tree is given in level-order (breadth-first), using null for missing children.

Hints

The closest value lies on the search path toward the key.
Descend the BST, keeping the value with the smallest |value - key| so far.
Break ties toward the smaller value, and stop early on an exact match.

Common doubts

The ordering means any subtree you skip is entirely farther from the key than the boundary node you visited, so the best candidate is always on the path.
No — one comparison decides the direction, keeping it O(height).
When two values are equally close, the smaller one is returned.

Interview follow-ups

The closest neighbour is whichever of the floor and ceil of the key is nearer — this descent finds it in one pass.
Use an inorder walk (sorted) plus a two-pointer or heap around the key's position.

Fun facts

  • The closest neighbour is always either the floor or the ceil of the key — never anything else.
  • This is BST binary search with a 'best so far' accumulator, the same idea as nearest-value search on a sorted array.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 11
Output: 10
10 and 12 are both distance 1 from 11; the smaller (10) is returned.
Example 2
Input: root = [8, 4, 12, 2, 6, 10, 14], key = 6
Output: 6
6 is in the tree — distance 0.
Constraints

- The number of nodes is in the range [1, 10^5] - 1 <= Node.val <= 10^6 - root is a valid BST - 1 <= key <= 10^6

Solve this problem →