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

# 270. Closest Binary Search Tree Value

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

BST上找与给定值最接近的。利用BST性质找target，cur->val比target小时结果只可能是当前点或右树的结点，遍历右树；反之则遍历左树，每个遍历到的结点都是候选。

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int closestValue(TreeNode* root, double target) {
        if (root == nullptr) return 0;
        int res = root->val;
        auto cur = root;
        while (cur != nullptr) {
            if (abs(cur->val - target) < abs(res - target)) res = cur->val;
            cur = cur->val < target ? cur->right : cur->left;
        }
        return res;
    }
};
```
