Closest Binary Search Tree Value
Real-world version: The Reading Nearest a TargetThe statement here is our own: the same inputs, outputs and technique.
A gauge tree is given as the flat list rig. It hangs from a single top joint, every joint carries at most two joints below it in a first and a second slot, and either slot may be empty. Every reading in the first slot and below is smaller than the joint's own, and every reading in the second slot and below is larger.
A flat list is read level by level: its first entry is the top joint's reading, and reading left to right, every entry that is not null claims the next two unused positions as its first and second slot in that order, while null marks an empty slot and claims no positions of its own.
Return the reading on the rig closest to target. Where two readings are equally close, return the smaller one.
Examples
Example 1
- Input
- rig = [8, 4, 12, 2, 6, 10, 14], target = 7.0
- Output
- 6
The readings 6 and 8 both sit one away from the target, and the smaller of the two is the answer.
Example 2
- Input
- rig = [5], target = 100.0
- Output
- 5
There is only one reading on the rig, so it is the closest by default.
Example 3
- Input
- rig = [2, 1, 3], target = 2.5
- Output
- 2
Both 2 and 3 sit half a unit from the target, so the smaller wins.
Constraints
- 1 <= rig.length <= 30000
- The rig holds between 1 and 10^4 joints.
- 0 <= rig[i] <= 10^9
- -10^9 <= target <= 10^9
- The first entry of the list is not null.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def closest_value(rig: list, target: float) -> int:public int closestValue(Integer[] rig, double target)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Two Sum IV - Input is a BSTReal-world version: Two Calibration Cards to a TargetEasy
- Range Sum of BSTReal-world version: Auditing a Fare Band in the RegisterEasy
- Minimum Absolute Difference in BSTReal-world version: Closest Two Readings in the Pressure IndexEasy
- Find Mode in Binary Search TreeReal-world version: Most Common Gauge OffsetEasy