LeetCode – Closest Binary Search Tree Value (Java)

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Java Solution 1 - Recursion

Recursively traverse down the root. When target is less than root, go left; when target is greater than root, go right.

public class Solution {
    int goal;
    double min = Double.MAX_VALUE;
 
    public int closestValue(TreeNode root, double target) {
        helper(root, target);
        return goal;
    }
 
    public void helper(TreeNode root, double target){
        if(root==null)
            return;
 
        if(Math.abs(root.val - target) < min){
            min = Math.abs(root.val-target);
            goal = root.val;
        } 
 
        if(target < root.val){
            helper(root.left, target);
        }else{
            helper(root.right, target);
        }
    }
}

Java Solution 2 - Iteration

public int closestValue(TreeNode root, double target) {
    double min=Double.MAX_VALUE;
    int result = root.val;
 
    while(root!=null){
        if(target>root.val){
 
            double diff = Math.abs(root.val-target);
            if(diff<min){
                min = Math.min(min, diff);
                result = root.val;
            }
            root = root.right;
        }else if(target<root.val){
 
            double diff = Math.abs(root.val-target);
            if(diff<min){
                min = Math.min(min, diff);
                result = root.val;
            }
            root = root.left;
        }else{
            return root.val;
        }
    }
 
    return result;
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. Bhanu on 2016-9-9

    I couldnt understand the following part of the code. can anyone explain

    if(Math.abs(root.val – target) < min){

    min = Math.abs(root.val-target);

    goal = root.val;

    }

  2. Harshad Sathe on 2016-11-26

    It finds the difference between the root value and target(ignores -ve sign) and basically remembers the min value which is “right now” closest to the target value in every recursive call

  3. Dennys Fredericci on 2017-5-24

    Hum, regarding to Big O…

    1) Both solutions has O(log n) time, is it correct?

    2) And what about space? The first solution spend more space than second solution because of the recursive method.

Leave a comment

*