EasyBinary Search TreeTreeDepth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary search tree (BST) and a floating-point number target.

Return the value stored in the tree that is closest to target, where closeness is measured by absolute difference. If two different node values are equally close to the target, return the smaller of the two values.

Example 1

Input: root = [4,2,5,1,3], target = 3.714286

Output: 4

Among the values, 4 is nearest to 3.714286 (distance about 0.286), closer than 3 (distance about 0.714).

Example 2

Input: root = [1], target = 4.428571

Output: 1

The tree holds only the value 1, so it is trivially the closest to the target.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4].
  • 0 <= Node.val <= 10^9
  • -10^9 <= target <= 10^9

After the pattern

Now solve one you haven't seen.

The Reading Nearest a Target is our own problem on the technique behind Closest Binary Search Tree Value: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free