AlgoFrames

Closest value

Challenge · Write code · about 15 min

Given the root of a binary search tree and a number target, return the key in the tree that is closest to target. If two keys are equally close, return the smaller one.

The tree is not empty.

Example 1

Input:

[[4,2,5,1,3],3.714286]

Output:

4

4 is 0.29 away; 3 is 0.71 away.

Example 2

Input:

[[4,2,5,1,3],2.5]

Output:

2

2 and 3 are equally close, so the smaller one is returned.

Constraints

  • 1 ≤ number of nodes ≤ 1,000
  • Keys are distinct integers with -1,000 ≤ key ≤ 1,000
  • -1,000 ≤ target ≤ 1,000

Learn the idea first: BST: search, insert, min and max, a visual lesson.

More BST: search, insert, min and max problems