Closest Binary Search Tree Value

class Solution {
    double diff;
    int result;
    public int closestValue(TreeNode root, double target) {
        diff = Double.MAX_VALUE;
        result = 0;
        helper(root, target);
        return result;
    }
    
    private void helper(TreeNode root, double target) {
        if (root == null) {
            return;
        }
        double newDiff = Math.abs(root.val - target);
        if (newDiff < diff) {
            result = root.val;
            diff = newDiff;
        }
        if (target < root.val) {
            helper(root.left, target);
        } else {
            helper(root.right, target);
        }
    }
}

最后更新于

这有帮助吗?