Closest Binary Search Tree Value

Easy Trees & BST BST Basics

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.
  • root is 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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (collect every value)O(n)O(n)
In-order with an early stopO(n)O(h)
Optimal (walk down the search path)O(h)O(1)

1Brute force (collect every value)

TimeO(n)The traversal visits each of the n nodes once, and the scan reads each value once.
SpaceO(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.

  1. Run an in-order traversal and append every value to a list vals (it comes out sorted).
  2. Set best = vals[0].
  3. For each v in vals, if |v - target| < |best - target|, set best = v.
  4. 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);
    }
}

2In-order with an early stop

TimeO(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.
SpaceO(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.

  1. Do an iterative in-order traversal: push the left spine, pop a node, then move to its right child.
  2. When the popped value v is at least target: if there is a prev and target - prev <= v - target, return prev; otherwise return v.
  3. Otherwise set prev = v and continue.
  4. 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;
    }
}

3Optimal (walk down the search path)

TimeO(h)The walk follows a single root-to-leaf path: about log n steps in a balanced tree, n in a chain.
SpaceO(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.

  1. Set best = root.val.
  2. While root is not null: let d = |root.val - target| and bd = |best - target|; if d < bd, or d == bd and root.val < best, set best = root.val.
  3. Move to root.left if target < root.val, otherwise to root.right.
  4. 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;
    }
}

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.