925. Closest Binary Search Tree Value

MediumTreesBSTBinary Search

Given the root of a binary search tree and an integer target, return the key in the BST that is closest in absolute value to the target. If two keys are equally close, return the smaller one. The input gives a level-order BST array and the target separated by ' | '.

Input: A level-order BST array and the target, separated by ' | '.

Output: Integer — the closest key.

Examples

Example 1
Input: [8,3,10,1,6,null,14] | 5
Output: 6
Explanation: 6 is the closest key to 5.
Example 2
Input: [4,2,7,1,3] | 6
Output: 7
Explanation: 7 is nearest to 6.
Example 3
Input: [5] | 3
Output: 5
Explanation: Only key.

Constraints

Asked by

MetaMicrosoftGoogleBloomberg
Solve this problem in the editor →