Clean and concise java solution


  • 92
    L
    public int closestValue(TreeNode root, double target) {
        int ret = root.val;   
        while(root != null){
            if(Math.abs(target - root.val) < Math.abs(target - ret)){
                ret = root.val;
            }      
            root = root.val > target? root.left: root.right;
        }     
        return ret;
    }

  • 1
    M

    clean solution !


  • -2

    I implemented recursive version of the same algorithm.

    public int closestValue(TreeNode root, double target) {
        double minDiff = Math.abs(root.val - target);
        int minVal = root.val;
        return closestValue(root, target, minDiff, minVal);
    }
    
    private int closestValue(TreeNode root, double target, double minDiff, int minVal) {
        if (root == null) {
            return minVal;
        }
        
        double currDiff = Math.abs(root.val - target);
        if (currDiff < minDiff) {
            minDiff = currDiff;
            minVal = root.val;
        }
        
        if (root.left == null && root.right == null) {
            return minVal;    
        }
    
        if (target == root.val) {
            return root.val;
         } else if (target < root.val) {
             return closestValue(root.left, target, minDiff, minVal);
         } else {
             return closestValue(root.right, target, minDiff, minVal);
         }
    }
    

  • 2

    Very clean and nice iteration solution.

    The recursion implementation should be like bellow:

    public class Solution {
        public int closestValue(TreeNode root, double target) {
            int a = root.val;
            if (a == target) return a;
            TreeNode kid = a < target ? root.right : root.left;
            if (kid == null) return a;
            int b = closestValue(kid, target);
            return Math.abs(a - target) < Math.abs(b - target) ? a : b;
        }
    }
    

  • 0

    very concise. I've got the same solution, only storing intermediate calculation of current best difference as possible optimization. But, typically the tree will not need so many comparisons so it's probably rather minor.

        public int ClosestValue(TreeNode root, double target) 
        {
            if (root == null) return 0;
            
            int val = root.val;
            double bestDiff = Math.Abs(target - val);
            TreeNode node = root;
            while (node != null)
            {
                double diff = Math.Abs(target - node.val);
                if (diff <= bestDiff)
                {
                    bestDiff = diff;
                    val = node.val;
                }
                node = target <= node.val ? node.left : node.right;
            }
            
            return val;
        }
    

  • 0
    T

    Very clean. I love this solution!


Log in to reply
 

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