Java Solution


  • 0
    public class Solution {
        public int closestValue(TreeNode root, double target) {
            if(root == null) return target > 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            
            if(target < root.val){
                int left_val = closestValue(root.left, target);
                return Math.abs(left_val-target) < Math.abs(root.val-target) ? left_val : root.val;
            }else if(target > root.val){
                int right_val =  closestValue(root.right, target);
                return Math.abs(right_val-target) < Math.abs(root.val-target) ? right_val : root.val;
            }else{
                return root.val;
            }
        }
    
    }
    ``

Log in to reply
 

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