- Closest Binary Search Tree Value
Closest Binary Search Tree Value
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.
Solution:
1. /*
2. * Definition for a binary tree node.
3. * public class TreeNode {
4. * int val;
5. * TreeNode left;
6. * TreeNode right;
7. * TreeNode(int x) { val = x; }
8. * }
9. /
10. public class Solution {
11. public int closestValue(TreeNode root, double target) {
12. int closest = root.val;
13. 14. while (root != null) {
15. if (Math.abs(root.val - target) < Math.abs(closest - target)) {
16. closest = root.val;
17. }
18. 19. if (target < root.val) {
20. root = root.left;
21. } else {
22. root = root.right;
23. }
24. }
25. 26. return closest;
27. }
28. }
