题目地址:
https://leetcode.com/problems/closest-binary-search-tree-value/
给定一棵二叉搜索树,每个节点的值都是整数,再给定一个浮点数target,问二叉搜索树中与target离的最近的数是多少。
思路是二分法。如果target小于树根,显然答案只存在于左子树或者树根本身;如果target大于树根,显然答案只存在于右子树或者树根本身。所以我们可以先判断target在哪个半边,求出那个半边与target离的最近的是哪个数,接着与树根做比较,得到最终的结果。代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int closestValue(TreeNode* root, double target) {
int closest = root->val;
const double epsilon = 1e-6;
auto cur = root;
while (cur) {
double diff = abs(target - cur->val);
double closestDiff = abs(target - closest);
if (diff < closestDiff)
closest = cur->val;
else if (abs(diff - closestDiff) < epsilon)
closest = min(closest, cur->val);
if (target < cur->val)
cur = cur->left;
else
cur = cur->right;
}
return closest;
}
};
时间复杂度 O ( h ) O(h) O(h),空间 O ( 1 ) O(1) O(1)。