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;
    }
};

Last updated