270. Closest Binary Search Tree Value

    
/*
* 270. Closest Binary Search Tree Value * 2016-6-25 by Mingyang */ public int closestValue(TreeNode root, double target) { int closest = root.val; double min = Double.MAX_VALUE; while(root!=null) { if( Math.abs(root.val - target) < min ) { min = Math.abs(root.val - target); closest = root.val; } if(target < root.val) { root = root.left; } else if(target > root.val) { root = root.right; } else { return root.val; } } return closest; }
    //下面就是recursive的方法,思路很清晰,就是root和左子树或者右子树进行比较大小
    public int closestValue1(TreeNode root, double target) {
        int a = root.val;
        TreeNode kid = target < a ? root.left : root.right;
        if (kid == null)
            return a;
        int b = closestValue1(kid, target);
        return Math.abs(a - target) < Math.abs(b - target) ? a : b;
    }
原文地址:https://www.cnblogs.com/zmyvszk/p/5619022.html