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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class Solution { public int closestValue(TreeNode root, double target) { int closet = root.val; while (root != null) { int r = root.val; closet = Math.abs(closet - target) > Math.abs(r - target) ? r : closet; root = r > target ? root.left : root.right; } return closet; } }
|