simple java solution


  • 0
    2
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int closestValue(TreeNode root, double target) {
            TreeNode t = root;
            double min = Double.MAX_VALUE;
            int ret = (int)target;
            while (t != null) {
                double d = Math.abs(target - t.val);
                if (d < min) {
                    min = d;
                    ret = t.val;
                }
                if (target > t.val) {
                    t = t.right;
                }
                else {
                    t = t.left;
                }
            }
            return ret;
        }
    }
    

Log in to reply
 

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