Problem 744
Floor and Ceil in a BST
Medium · 20 pts · Tree, Binary Search Tree
Problem
Given a binary search tree with distinct values and a key X, find the floor (the largest value in the tree that is at most X) and the ceil (the smallest value that is at least X). Print -1 for one that does not exist. Walk down from the root once: when a node's value is at most X, it is a floor candidate and the search continues to the right; otherwise it is a ceil candidate and the search continues to the left.
Input
The first line contains X. 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 floor and the ceil of X separated by a space, using -1 when one does not exist.
Constraints
1 <= number of nodes <= 10000; 0 <= values, X <= 10^9; values are distinct
Example input
11 7 8 4 12 2 6 10 14
Example output
10 12
Explanation
The BST 8 4 12 2 6 10 14 holds 2 4 6 8 10 12 14. For X = 11 the largest value not above 11 is 10 and the smallest not below 11 is 12, so the answer is 10 12.