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.
思路:就是traverse,记录一个diff,然后logn去搜,搜到底,就可以了;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
double diff = Double.MAX_VALUE;
while(root != null) {
if(root.val == target) {
return root.val;
} else if(root.val < target) {
if(target - root.val < diff) {
diff = target - root.val;
res = root.val;
}
root = root.right;
} else {
// root.val > target;
if(root.val - target < diff) {
diff = root.val - target;
res = root.val;
}
root = root.left;
}
}
return res;
}
}