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,递归
递归的原理是,如果target<root.val, 那么最接近值只会是root或者存在于root的左子树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
int a = root.val;
TreeNode kid = a < target? root.right: root.left;
if(kid == null) return a;
int b = closestValue(kid, target);
if(Math.abs(a-target)<Math.abs(b-target)) return a;
else return b;
}
}
方法二,iteration
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
int closest = root.val;
while(root!=null){
if(Math.abs(closest-target) >= Math.abs(root.val - target))
closest = root.val;
root = target < root.val? root.left: root.right;
}
return closest;
}
}
二刷
同上
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int closestValue(TreeNode root, double target) {
if((double)root.val == target) return root.val;
if(target<root.val && root.left == null) return root.val;
if(target>root.val && root.right == null) return root.val;
if(target<root.val){
int left = closestValue(root.left, target);
if(Math.abs(root.val - target)< Math.abs(left - target))
return root.val;
else return left;
}
if(target > root.val){
int right = closestValue(root.right, target);
if(Math.abs(root.val - target)< Math.abs(right - target))
return root.val;
else return right;
}
return 0;
}
}