> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0270-closest-binary-search-tree-value.md).

# 0270. Closest Binary Search Tree Value

<https://leetcode.com/problems/closest-binary-search-tree-value>

## Description

Given the `root` of a binary search tree and a `target` value, return *the value in the BST that is closest to the* `target`.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/03/12/closest1-1-tree.jpg)

```
**Input:** root = [4,2,5,1,3], target = 3.714286
**Output:** 4
```

**Example 2:**

```
**Input:** root = [1], target = 4.428571
**Output:** 1
```

**Constraints:**

* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 109`
* `-109 <= target <= 109`

## ac

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;

        while (root != null) {
            res = Math.abs(target - res) < Math.abs(target - root.val) ? res : root.val;

            if (target == root.val) {
                break;
            } else if (target < root.val) {
                root = root.left;
            } else {
                root = root.right;
            }
        }

        return res;
    }
}
```
