Skip to content
BytePatterns

Closest Key in a BST

EasyTrees & BST#bst#search-path~15m

Problem

A binary search tree stores distinct whole-number keys. Given its root and a target that may have a fractional part, return the key closest to the target. If two keys are equally close, return the smaller one. The tree always has at least one node.

Examples

Input:  tree = 8, left 3 with children 1 and 6 (6 has children 4 and 7),
        right 10 with a right child 14; target = 5
Output: 4
Why:    4 and 6 are both one away, and 4 is the smaller
Input:  same tree; target = 12.2
Output: 14
Why:    14 is 1.8 away while 10 is 2.2 away
Input:  tree = a single node 7; target = -100
Output: 7
Why:    edge case, the only key is the closest one

Hints

0 / 3

Stuck on the idea rather than the code? BST Insert and Search covers it.