Closest Binary Search Tree Value

Problem

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If there are multiple answers, print the smallest.

Example 1:

Input: root = [4,2,5,1,3], target = 3.714286
Output: 4

Example 2:

Input: root = [1], target = 4.428571
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 109
  • -109 <= target <= 109

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        var closest = root.val;
        while (root != null) {
            var val = root.val;
            var d1 = Math.abs(val - target);
            var d2 = Math.abs(closest - target);
            if (d1 < d2 || (d1 == d2 && val < closest)) {
                closest = val;
            }
            root = target < val ? root.left : root.right;
        }
        return closest;
    }
}

Recent posts from blogs that I like

Concurrent Servers: Part 7 - Rust

This is part 7 in a series of posts on writing concurrent network servers. In this part, we discuss how the challenges described in earlier parts are tackled in the Rust programming language. All posts in the series: Part 1 - Introduction Part 2 - Threads Part 3 - Event-driven Part 4 - libuv Part 5 ...

via Eli Bendersky

A volcanic weekend of paintings 1 Fuji to Hekla

Mount Fuji by Hokusai, Naotake, Hiroshige, and pioneer botanical painter Marianne North. Childe Hassam's Mounts Adams and St Helens, Church's Cotopaxi, and others.

via The Eclectic Light Company

Amp is so good and so bad

The highs and lows of using Amp and its remote-first approach to software development.

via Jacob Woliver