# 270. Closest Binary Search Tree Value

![](/files/-MjdsNsOxSaNXQcLCHyM)

![](/files/-MjdsQBOWt_B7EVDA-GH)

iteration, 左右走去找到 upper, lower, 最後比較差值

time: O(h), tree height

space: O(1)

可以參考這個

<https://www.jiuzhang.com/problem/closest-binary-search-tree-value/>

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int closestValue(TreeNode root, double target) {
        
        TreeNode upper = root;
        TreeNode lower = root;
        while (root != null) {
            if (root.val > target) {
                upper = root;
                root = root.left;
            } else if (root.val < target) {
                lower = root;
                root = root.right;
            } else {
                return root.val;
            }
        }
        if (Math.abs(upper.val - target) > Math.abs(target - lower.val)) {
            return lower.val;
        }
        return upper.val;
    }
}
```

更精簡的

```java
class Solution {
  public int closestValue(TreeNode root, double target) {
    int val;
    int closest = root.val;
    while(root != null) {
      val = root.val;
      closest = Math.abs(val - target) > Math.abs(closest - target) ? closest : val;
      root = root.val < target ? root.right: root.left;
    }
    
    return closest;
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/tree/270.-closest-binary-search-tree-value.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
