Problem 921
Closest Binary Search Tree Value
Easy · 10 pts · Tree, Binary Search Tree, Binary Search
Problem
Given a binary search tree with distinct values and an integer TARGET, find the value in the tree closest to TARGET. If two values are equally close, print the smaller one. Walk down from the root like a binary search: at each node update the best answer, then go left if TARGET is smaller than the node's value and right otherwise. This takes O(height) time.
Input
The first line contains TARGET. The next two lines describe the BST: N, the number of tokens, then N level-order tokens with 'null' for missing children.
Output
Print the closest value.
Constraints
1 <= number of nodes <= 10000; 0 <= values, TARGET <= 10^9; values are distinct
Example input
4 5 4 2 5 1 3
Example output
4
Explanation
In the BST 4 2 5 1 3 with TARGET = 4, the value 4 is in the tree, so it is the closest. For TARGET = 6 the answer would be 5.