FunctionRacerProblemsRace

Floor and Ceiling in a BST

EasyTreesPython, JavaScript, TypeScript

You are given the root of a binary tree. The floor of x is the largest value in the BST that is less than or equal to x. The ceiling is the smallest value that is greater than or equal to x. Return [floor, ceiling]. Use None for one that does not exist (for example when x is smaller than everything, the floor is None). In a binary search tree every value in a left subtree is smaller than its node and every value in a right subtree is larger.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [8,4,12,2,6,10,14]
x 5
returns [4,6]

Floor 4, ceiling 6.

Example 2

root [8,4,12]
x 1
returns [null,4]

Nothing is at most 1, so the floor is None; the ceiling is 4.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems