Smallest Stored Value That Is Not Below a Number

Implement ceilOf

You are given the root of a binary search tree with distinct values and an integer x. Return the smallest value in the tree that is greater than or equal to x (the "ceiling" of x). If every value in the tree is smaller than x, or the tree is empty, return -1.

Listing all values in order works, but the search-tree property lets you find the answer by walking a single path from the root and remembering the best candidate so far.

Example 1:

Input: root = [60,25,85,10,40,70,95,null,null,35,50], x = 38

Output: 40

Example 2:

Input: root = [60,25,85,10,40,70,95,null,null,35,50], x = 99

Output: -1

Example 3:

Input: root = [60,25,85,10,40,70,95,null,null,35,50], x = 70

Output: 70

+ 14 hidden test cases run on Submit.

Constraints:

  • ●0 ≤ number of nodes ≤ 100; all node values are distinct, 0 ≤ node.val ≤ 1000
  • ●The tree is a binary search tree (left subtree smaller, right subtree larger at every node), given by its root node
  • ●0 ≤ x ≤ 1000
  • ●Return the smallest value in the tree that is greater than or equal to x (x itself counts). If every value is smaller than x, or the tree is empty, return -1

root =

[60, 25, 85, 10, 40, 70, 95, null, null, 35, 50]

x =

38