Problem Description:
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.
思路:
1. 需要提取利用的信息:BST每一层root的值。比较root->val-target和closest-target,在每一层比较然后决定是否更新closest。
2. 利用BST, O(n)复杂度
3. recursive vs iterative
int closestValue(TreeNode* root, double target) {
//iterative
int closest=root->val;
while(root){
if(abs(target-root->val)<=abs(target-closest))
closest=root->val;
root=target>=root->val?root->right:root->left;
}
return closest;
}
int closestValue(TreeNode* root, double target) {
//recursive
int a=root->val;
auto nextRoot=target>=a?root->right:root->left;
if(nextRoot==NULL) return a;
int b=closestValue(nextRoot,target);
return abs(a-target)<=abs(b-target)?a:b;
}