My simple solution in JAVA with explanation;


  • 0
    1. Start from the root, if the root value is bigger (smaller) than target value, the closest value must be the root value or the value in root's left(right) sub tree. Use diff to save the smallest difference.
    2. Go to the sub tree and repeat the process until it reaches null;

    public class Solution {
    int closest = Integer.MAX_VALUE;
    double diff = 0;
    boolean first = true;
    public int closestValue(TreeNode root, double target) {
        if(root == null) return closest;
        if(first) 
        {
            first = false;
            diff = Math.abs(target - root.val);
            closest = root.val;
        }
        else if(Math.abs(target - root.val) < diff)
        {
            diff = Math.abs(target - root.val);
            closest = root.val;
        }
       
        return target>root.val?closestValue(root.right,target):closestValue(root.left,target);
    }
    

    }


  • 0
    L

    I do not think you need the first marker..


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.