A music app stores its tempo presets in a binary search tree. When a user types a tempo, the app snaps it to the nearest preset and also shows the presets just below and just above it.
A node is a plain object { value, left, right }, where value is a finite number and left/right are nodes or null. Every value in a node's left subtree is smaller than the node's value, every value in its right subtree is larger, and no value appears twice. root may be null for an empty tree.
Write two functions:
floorAndCeiling(root, target) returns [floor, ceiling]: the largest value <= target and the smallest value >= target. Either is null when no such value exists.
closestValue(root, target) returns the value with the smallest distance |value - target|, or null for an empty tree.
Rules:
If the floor and the ceiling are equally far from target, return the smaller value.
If target is in the tree, both functions use it: floorAndCeiling returns [target, target].
If target is not a finite number, throw a TypeError.
Do not change the tree.
The tests ask 100,000 questions of a tree with 100,000 nodes, so a question must walk one path from the root (O(h)), not visit every node.
const node = (value, left = null, right = null) => ({ value, left, right });const root = node(40, node(20, node(10), node(30)), node(60, node(50), node(70)));closestValue(root, 33); // 30floorAndCeiling(root, 33); // [30, 40]closestValue(root, 45); // 40: 40 and 50 are equally close, the smaller winsfloorAndCeiling(root, 5); // [null, 10]closestValue(null, 5); // null
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.