版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85918356
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
样例
Given root = {1}
, target = 4.428571
, return 1
.
注意事项
- 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性质遍历。
/**
* 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
TreeNode curNode = root;
int cloVal = root.val;
while(curNode != null){
if(Math.abs(target - curNode.val) < Math.abs(target - cloVal))
cloVal = curNode.val;
if(target > curNode.val){
curNode = curNode.right;
}else if(target < curNode.val){
curNode = curNode.left;
}
}
return cloVal;
}
}
解题思路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);
}
}