KatInterview

Nearest Node in a Binary Search Tree

Trees & GraphsAuto-graded · 20 test cases
EasyAuto-gradedTrees & Graphstrees-graphsbinary-search-treesearch

Last updated

Find the value in a Binary Search Tree represented as a level-order array that has the smallest absolute difference to a target number.

Given the level-order array representation of a valid non-empty Binary Search Tree (BST) and a floating-point number target, determine the node value within the tree that is closest in absolute value to target.

The tree structure is provided as a list a in standard LeetCode level-order format (where missing child nodes are represented by None). The nodes contain unique integer values, and it is guaranteed that there is a single unique value in the tree closest to target.

Constraints

  • 1 <= len(a) <= 10^4
  • -10^9 <= val <= 10^9 for every non-None element in a.
  • a[0] is guaranteed to be an integer (non-None).
  • -10^9 <= target <= 10^9
  • There is a uniquely closest value in the tree to target.

Examples

Example 1

Input: find_closest_value([4, 2, 5, 1, 3], 3.714286)

Output: 4

Example 2

Input: find_closest_value([1], 4.428571)

Output: 1

Hints

Hint 1

Consider how you can traverse down the tree efficiently by using the standard binary search tree property.

Hint 2

At each step down the path, check if the current node's value is closer to target than the best value observed so far.

Hint 3

Decide whether to move to the left or right child depending on whether target is less than or greater than the current node's value.