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.
Example:
Input: root = [4,2,5,1,3], target = 3.714286
4
/ \
2 5
/ \
1 3
Output: 4
Solution:
/**
* 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[] close = new int[]{root.val};
helper(root, target, close);
return close[0];
}
private void helper(TreeNode root, double target, int[] close) {
if (root == null) return;
if (Math.abs(target - root.val) < Math.abs(target - close[0])) {
close[0] = root.val;
}
if (root.val > target) {
helper(root.left, target, close);
} else {
helper(root.right, target, close);
}
}
}