题目描述
给定一个不为空的二叉搜索树和一个目标值 target,请在该二叉搜索树中找到最接近目标值 target 的数值。
注意:
给定的目标值 target 是一个浮点数
题目保证在该二叉搜索树中只会存在一个最接近目标值的数
示例:
输入: root = [4,2,5,1,3],目标值 target = 3.714286
4
/ \
2 5
/ \
1 3
输出: 4
题解
递归;也可用上下边界二分,或者用栈替代递归。
abs是整型取绝对值;
fabs是浮点数取绝对值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int closestValue(struct TreeNode* root, double target){
int output;
double sub;
int left;
int right;
if (!root) return 0xFFFFFFFF;
//if (!root->left && !root->right) return root->val;
sub = root->val - target;
if (sub == 0) return root->val;
if (sub > 0) {
left = closestValue(root->left, target);
if (left != 0xFFFFFFFF) return (fabs(left - target) < fabs(sub)) ? left : root->val;
return root->val;
}else {
right = closestValue(root->right, target);
if (right != 0xFFFFFFFF) return (fabs(right - target) < fabs(sub)) ? right : root->val;
return root->val;
}
return root->val;
}
测试用例
[2,0,33,null,1,25,40,null,null,11,31,34,45,10,18,29,32,null,36,43,46,4,null,12,24,26,30,null,null,35,39,42,44,null,48,3,9,null,14,22,null,null,27,null,null,null,null,38,null,41,null,null,null,47,49,null,null,5,null,13,15,21,23,null,28,37,null,null,null,null,null,null,null,null,8,null,null,null,17,19,null,null,null,null,null,null,null,7,null,16,null,null,20,6]
0.428571
[28,12,45,4,24,35,47,2,9,14,25,31,42,46,48,0,3,8,11,13,20,null,26,30,33,41,43,null,null,null,49,null,1,null,null,7,null,10,null,null,null,17,22,null,27,29,null,32,34,36,null,null,44,null,null,null,null,6,null,null,null,16,18,21,23,null,null,null,null,null,null,null,null,null,37,null,null,5,null,15,null,null,19,null,null,null,null,null,40,null,null,null,null,null,null,39,null,38]
2.000000