Share my simple Java recursive solution

  • 0
    double diff = Double.MAX_VALUE;
    int closetVal = -1;
    public int closestValue(TreeNode root, double target) {
        double newDiff = Math.abs(target-root.val);
        if(diff > newDiff){
            diff = newDiff;
            closetVal = root.val;
        if(root.left==null && root.right==null) return closetVal;
        if(root.left==null) return closestValue(root.right, target);
        else if(root.right==null) return closestValue(root.left, target);
            if(root.val<target) return closestValue(root.right, target);
            else return closestValue(root.left, target);

Log in to reply

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