问题描述
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
- Given target value is a floating point.
- You are guaranteed to have only one unique value in the BST that is closest to the target.
思路分析
给一棵二叉搜索树和一个浮点数target,找到树中和target最接近的值。
利用二叉搜索树的性质,可以用递归或者循环的方式搜索整棵树。
循环使用一个指针,先进行判断当前结点值与target的关系,然后根据二叉树性质,小于target就搜索左子树,否则搜索右子树。
递归使用的是前序遍历的方式,需要注意因为是void,一定要记得设置结束条件,结点为null的时候要返回。
代码
循环
/**
* 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) {
int result = root->val;
while(root){
if (abs((double)root->val - target) < abs((double)result - target))
result = root->val;
if ((double)root->val > target)
root = root->left;
else
root = root->right;
}
return result;
}
};
时间复杂度:
O(logn)
空间复杂度:
O(1)
递归
/**
* 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) {
int result = root->val;
getClosest(root, result, target);
return result;
}
void getClosest(TreeNode* root, int& result, double target){
if (!root)
return;
if (abs((double)root->val - target) < abs((double)result - target))
result = root->val;
getClosest(root->left, result, target);
getClosest(root->right, result, target);
}
};
时间复杂度:
O(n)
空间复杂度:
O(1)
反思
对于遍历,本质上就是指针的移动,找好移动的判断条件即可。
学了新的一招void函数的递归用法,&引用很关键,每次只对那一个内存位置进行操作。还有就是一定要记得设置结束条件。
可以改进递归算法,将result直接作为一个double进行操作,最后再转换回来,会省一点时间。
/**
* 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) {
double result = (double)root->val;
getClosest(root, result, target);
return (int)result;
}
void getClosest(TreeNode* root, double& result, double target){
if (!root)
return;
if (abs(root->val - target) < abs(result - target))
result = root->val;
getClosest(root->left, result, target);
getClosest(root->right, result, target);
}
};