# Closest Binary Search Tree Value

{% tabs %}
{% tab title="Java" %}

```java
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);
        }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
class Solution(object):
    def closestValue(self, root, target):
        r = root.val
        while root:
            if abs(root.val - target) < abs(r - target):
                r = root.val
            root = root.left if target < root.val else root.right
        return r
```

{% endtab %}
{% endtabs %}

![](https://2784211123-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M-ELB26IpzCEJWSDi0m%2F-M-ELbsic2B8wwsarT-C%2F-M-EMqc6UhBUlpM3zyHy%2F1580805867266.jpg?alt=media\&token=11a20b67-9e32-4c02-bf02-c405dac8ef0f)
