Largest Stored Value That Does Not Exceed a Number

Implement floorOf

You are given the root of a binary search tree with distinct values and an integer x. Return the largest value in the tree that is less than or equal to x (the "floor" of x). If every value in the tree is larger 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 one path from the root, remembering the best candidate so far.

Example 1:

Input: root = [55,30,80,15,45,65,95,null,null,40,50], x = 48

Output: 45

Example 2:

Input: root = [55,30,80,15,45,65,95,null,null,40,50], x = 10

Output: -1

Example 3:

Input: root = [55,30,80,15,45,65,95,null,null,40,50], x = 65

Output: 65

+ 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 largest value in the tree that is less than or equal to x (x itself counts). If every value is larger than x, or the tree is empty, return -1

root =

[55, 30, 80, 15, 45, 65, 95, null, null, 40, 50]

x =

48