Closest Binary Search Tree Value
Closest Binary Search Tree Value is a easy trees & bst problem solved with the bst basics pattern.
The best approach, optimal (walk down the search path), runs in O(h) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (collect every value) up.
Problem
You are given the root of a binary search tree and a real number target. Return the value in the tree that is closest to target, that is, the value v for which |v - target| is as small as possible.
If two values are equally close (the target sits exactly halfway between them), return the smaller of the two.
The tree has at least one node, and all its values are distinct.
Examples
Example 1
- Input
root = [8, 3, 10, 1, 6, null, 14, null, null, 4, 7], target = 5.2- Output
6- Why
- The two values around 5.2 are 4 and 6. 4 is 1.2 away and 6 is only 0.8 away, so 6 wins. Every other value is farther still.
Example 2
- Input
root = [2, 1, 3], target = 2.5- Output
2- Why
- 2 and 3 are both exactly 0.5 away. On a tie the smaller value is the answer, so it is 2.
Example 3
- Input
root = [20, 10, 30, null, 15], target = 1000000.0- Output
30- Why
- The target is far above every value, so the largest value in the tree, 30, is the closest one.
Constraints
- The number of nodes in the tree is in the range
[1, 10^4]. 0 <= Node.val <= 10^9, and all values are distinct.rootis a valid binary search tree.-10^9 <= target <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (collect every value) | O(n) | O(n) |
| In-order with an early stop | O(n) | O(h) |
| Optimal (walk down the search path) | O(h) | O(1) |
1Brute force (collect every value)
O(n)The traversal visits each of the n nodes once, and the scan reads each value once.O(n)The list holds all n values, and the recursion goes as deep as the tree.Ignore the search-tree order at first. Collect every value with an in-order traversal, then scan the list and keep the value with the smallest distance to the target. In-order gives the values in increasing order, so if we replace the best only on a strictly smaller distance, a tie keeps the earlier, smaller value automatically.
- Run an in-order traversal and append every value to a list
vals(it comes out sorted). - Set
best = vals[0]. - For each
vinvals, if|v - target| < |best - target|, setbest = v. - Return
best.
class Solution {
public int closestValue(TreeNode root, double target) {
List<Integer> vals = new ArrayList<>();
inorder(root, vals);
int best = vals.get(0);
for (int v : vals) {
if (Math.abs(v - target) < Math.abs(best - target)) best = v;
}
return best;
}
private void inorder(TreeNode node, List<Integer> vals) {
if (node == null) return;
inorder(node.left, vals);
vals.add(node.val);
inorder(node.right, vals);
}
}class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
vals = []
self.inorder(root, vals)
best = vals[0]
for v in vals:
if abs(v - target) < abs(best - target):
best = v
return best
def inorder(self, node: Optional[TreeNode], vals: List[int]) -> None:
if node is None:
return
self.inorder(node.left, vals)
vals.append(node.val)
self.inorder(node.right, vals)class Solution {
public:
int closestValue(TreeNode* root, double target) {
vector<int> vals;
inorder(root, vals);
int best = vals[0];
for (int v : vals) {
if (fabs(v - target) < fabs(best - target)) best = v;
}
return best;
}
private:
void inorder(TreeNode* node, vector<int>& vals) {
if (!node) return;
inorder(node->left, vals);
vals.push_back(node->val);
inorder(node->right, vals);
}
};function closestValue(root, target) {
const vals = [];
inorder(root, vals);
let best = vals[0];
for (const v of vals) {
if (Math.abs(v - target) < Math.abs(best - target)) best = v;
}
return best;
}
function inorder(node, vals) {
if (node === null) return;
inorder(node.left, vals);
vals.push(node.val);
inorder(node.right, vals);
}2In-order with an early stop
O(n)In the worst case (target above every value) the traversal still visits all n nodes, but it stops early as soon as it passes the target.O(h)The stack holds one root-to-node path, at most h nodes.The in-order sequence is sorted, so the answer is one of two neighbours: the last value below the target (call it prev) and the first value at or above it. Walk the in-order sequence with an explicit stack and stop as soon as a value reaches the target. Compare it with prev: if prev is at least as close, return prev (it is smaller, so it also wins a tie); otherwise return the current value. If no value reaches the target, every value is below it and the last one, the maximum, is the answer.
- Do an iterative in-order traversal: push the left spine, pop a node, then move to its right child.
- When the popped value
vis at leasttarget: if there is aprevandtarget - prev <= v - target, returnprev; otherwise returnv. - Otherwise set
prev = vand continue. - If the traversal ends, return
prev, the largest value.
class Solution {
public int closestValue(TreeNode root, double target) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
Integer prev = null;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if (cur.val >= target) {
if (prev != null && target - prev <= cur.val - target) return prev;
return cur.val;
}
prev = cur.val;
cur = cur.right;
}
return prev;
}
}class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
stack = []
cur = root
prev = None
while cur is not None or stack:
while cur is not None:
stack.append(cur)
cur = cur.left
cur = stack.pop()
if cur.val >= target:
if prev is not None and target - prev <= cur.val - target:
return prev
return cur.val
prev = cur.val
cur = cur.right
return prevclass Solution {
public:
int closestValue(TreeNode* root, double target) {
stack<TreeNode*> st;
TreeNode* cur = root;
bool hasPrev = false;
int prev = 0;
while (cur || !st.empty()) {
while (cur) {
st.push(cur);
cur = cur->left;
}
cur = st.top();
st.pop();
if (cur->val >= target) {
if (hasPrev && target - prev <= cur->val - target) return prev;
return cur->val;
}
prev = cur->val;
hasPrev = true;
cur = cur->right;
}
return prev;
}
};function closestValue(root, target) {
const stack = [];
let cur = root;
let prev = null;
while (cur !== null || stack.length > 0) {
while (cur !== null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if (cur.val >= target) {
if (prev !== null && target - prev <= cur.val - target) return prev;
return cur.val;
}
prev = cur.val;
cur = cur.right;
}
return prev;
}3Optimal (walk down the search path)
O(h)The walk follows a single root-to-leaf path: about log n steps in a balanced tree, n in a chain.O(1)Only the current node and the best value are kept; no recursion and no stack.Search for the target as if it were in the tree. At each node, if the target is smaller go left, otherwise go right, and update the best value whenever the current node is closer, or equally close and smaller. The walk passes both the largest value below the target and the smallest value above it, because each of them is the last node where the search turns towards the target from that side, so the best value on the path is the closest value in the whole tree.
- Set
best = root.val. - While
rootis not null: letd = |root.val - target|andbd = |best - target|; ifd < bd, ord == bdandroot.val < best, setbest = root.val. - Move to
root.leftiftarget < root.val, otherwise toroot.right. - Return
best.
class Solution {
public int closestValue(TreeNode root, double target) {
int best = root.val;
while (root != null) {
double d = Math.abs(root.val - target);
double bd = Math.abs(best - target);
if (d < bd || (d == bd && root.val < best)) best = root.val;
root = target < root.val ? root.left : root.right;
}
return best;
}
}class Solution:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
best = root.val
while root is not None:
d = abs(root.val - target)
bd = abs(best - target)
if d < bd or (d == bd and root.val < best):
best = root.val
root = root.left if target < root.val else root.right
return bestclass Solution {
public:
int closestValue(TreeNode* root, double target) {
int best = root->val;
while (root) {
double d = fabs(root->val - target);
double bd = fabs(best - target);
if (d < bd || (d == bd && root->val < best)) best = root->val;
root = target < root->val ? root->left : root->right;
}
return best;
}
};function closestValue(root, target) {
let best = root.val;
while (root !== null) {
const d = Math.abs(root.val - target);
const bd = Math.abs(best - target);
if (d < bd || (d === bd && root.val < best)) best = root.val;
root = target < root.val ? root.left : root.right;
}
return best;
}Edge cases to test
- A single node: its value is the answer, however far away the target is
- The target equals a value in the tree: that value is at distance 0
- The target lies below every value, or above every value: the answer is the minimum or the maximum
- A tie, with the target exactly halfway between two values: return the smaller one, even when the larger one is met first on the way down
- A skewed tree that is really a chain, so the walk down can take n steps
- A target that is not a whole number: keep it and the distances as doubles; rounding the target to an int first can pick the wrong neighbour
Hints
Hint 1
The simplest correct answer looks at every value and keeps the one with the smallest distance. How does a sorted order make the tie rule easy?
Hint 2
An in-order traversal visits the values in increasing order. The answer is either the last value below the target or the first value at or above it.
Hint 3
You do not need to visit the whole tree. At each node the target is either to its left or to its right, so walk down one path, like a search, and remember the best value seen on the way.
Hint 4
The value just below the target and the value just above it both lie on that search path, so the best value on the path is the answer.
FAQ
What is the best time complexity for Closest Binary Search Tree Value?
Optimal (walk down the search path) runs in O(h) time and O(1) extra space. The walk follows a single root-to-leaf path: about log n steps in a balanced tree, n in a chain.
Which pattern does Closest Binary Search Tree Value use?
It is a trees & bst problem that uses the bst basics pattern. Other problems with the same pattern: Search in a Binary Search Tree, Minimum element in BST, Insert into a Binary Search Tree.
Is there a brute force solution for Closest Binary Search Tree Value?
Yes. Brute force (collect every value) takes O(n) time and O(n) space. Ignore the search-tree order at first.
Which edge cases should I test for Closest Binary Search Tree Value?
A single node: its value is the answer, however far away the target is; The target equals a value in the tree: that value is at distance 0; The target lies below every value, or above every value: the answer is the minimum or the maximum; A tie, with the target exactly halfway between two values: return the smaller one, even when the larger one is met first on the way down; A skewed tree that is really a chain, so the walk down can take n steps; A target that is not a whole number: keep it and the distances as doubles; rounding the target to an int first can pick the wrong neighbour.