Nearest Node in a Binary Search Tree
Trees & GraphsAuto-graded · 20 test casesLast 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^9for every non-Noneelement ina.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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution consists of two main parts:
- Reconstructing Tree Structure: Parse the level-order array representation into child pointer indices (
leftandrightarrays) using a breadth-first search queue. - BST Search: Perform a binary search starting at the root node (index 0).
At each step in the search:
- Calculate
abs(current_value - target)and update the recorded best candidate if this distance is strictly smaller than the current minimum distance. - If
target < current_value, descend into the left child because all nodes in the right subtree are greater thancurrent_valueand thus even further away fromtarget. - If
target > current_value, descend into the right child for symmetric reasons. - If
target == current_value, the distance is0, so we can exit immediately.
Complexity
- Time Complexity: $\mathcal{O}(n)$, where $n$ is the length of array
a. Reconstructing child links takes $\mathcal{O}(n)$ time. The tree traversal takes $\mathcal{O}(h)$ steps (where $h$ is tree height, at most $n$). - Space Complexity: $\mathcal{O}(n)$ auxiliary space to store the parent-child relationships and BFS queue.
Python Source Code
from collections import deque
from typing import List, Optional
def find_closest_value(a: List[Optional[int]], target: float) -> int:
vals = a
n = len(vals)
left = [-1] * n
right = [-1] * n
q = deque([0])
idx = 1
# Reconstruct left and right child pointers for each index
while q and idx < n:
u = q.popleft()
if idx < n and vals[idx] is not None:
left[u] = idx
q.append(idx)
idx += 1
if idx < n and vals[idx] is not None:
right[u] = idx
q.append(idx)
idx += 1
best = vals[0]
best_dist = abs(vals[0] - target)
cur = 0
# Traverse down the BST
while cur != -1:
v = vals[cur]
d = abs(v - target)
if d < best_dist:
best_dist = d
best = v
if target < v:
cur = left[cur]
elif target > v:
cur = right[cur]
else:
break
return best