An inorder traversal of a BST produces values in sorted order. By collecting all values first, we can then find the one closest to the target using a simple linear search. While not the most efficient approach, it clearly demonstrates the relationship between inorder traversal and sorted order.
Where is the total number of nodes in the binary tree
Since inorder traversal gives sorted values, we can stop early once we find the first value greater than or equal to the target. At that point, the answer is either the current value or the previous value we visited (the predecessor). This avoids traversing the entire tree when the target is small.
predecessor <= target < current value, compare both and return the closer one.class Solution:
def closestValue(self, root: TreeNode, target: float) -> int:
stack, pred = [], float('-inf')
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if pred <= target and target < root.val:
return min(pred, root.val, key = lambda x: abs(target - x))
pred = root.val
root = root.right
return predWhere is an index of the closest element and is the height of the tree.
The BST property allows us to use binary search. At each node, we compare the target with the current value to decide whether to go left or right. We track the closest value seen so far. If the target is smaller, we go left (there might be a closer smaller value). If the target is larger, we go right (there might be a closer larger value). This approach only visits nodes along a single path from root to leaf.
Where is the height of the tree.
When two values have the same distance to the target, the problem requires returning the smaller value. Using < instead of <= in the comparison can return the wrong answer.
# Wrong: Returns larger value on ties
if abs(val - target) < abs(closest - target):
closest = val
# Correct: Prefer smaller value on ties
if abs(val - target) < abs(closest - target) or \
(abs(val - target) == abs(closest - target) and val < closest):
closest = valChoosing the wrong child based on comparison with target defeats the purpose of binary search. If target is smaller than current value, you must go left (not right) to find potentially closer smaller values.