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.
/**
* 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) {
TreeNode kidNode = root.val < target? root.right: root.left;
if (kidNode == null) return root.val;
int kidval = closestValue(kidNode, target);
return Math.abs(kidval - target) < Math.abs(root.val - target)? kidval: root.val;
}
}
如果用迭代求解,代码如下:
public int closestValue(TreeNode root, double target) {
int ret = root.val;
while(root != null){
if(Math.abs(target - root.val) < Math.abs(target - ret)){
ret = root.val;
}
root = root.val > target? root.left: root.right;
}
return ret;
}