给一棵非空二叉搜索树以及一个target值,找到在BST中最接近给定值的节点值
样例
样例1
输入: root = {5,4,9,2,#,8,10} and target = 6.124780
输出: 5
样例2
输入: root = {3,2,4,1} and target = 4.142857
输出: 4
注意事项
- 给出的目标值为浮点数
- 我们可以保证只有唯一一个最接近给定值的节点
解题思路1:
非递归,使用cnt变量存储当前最小差值,res为最接近的值。然后依照BST性质遍历。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the given BST
* @param target: the given target
* @return: the value in the BST that is closest to the target
*/
public int closestValue(TreeNode root, double target) {
// write your code here
double cnt = Double.MAX_VALUE; //记录最小差值
int res = 0;
while(root != null){
if(Math.abs(target - root.val) < cnt){
cnt = Math.abs(target - root.val);
res = root.val;
}
if(target > root.val)
root = root.right;
else
root = root.left;
}
return res;
}
}
解题思路2:
递归,思路同上。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: the given BST
* @param target: the given target
* @return: the value in the BST that is closest to the target
*/
public int closestValue(TreeNode root, double target) {
// write your code here
res = root.val;
helper(root, target);
return res;
}
private int res;
private void helper(TreeNode root, double target){
if(root == null)
return;
if(Math.abs(target - root.val) < Math.abs(target - res))
res = root.val;
if(target > root.val)
helper(root.right, target);
else
helper(root.left, target);
}
}