Closest Binary Search Tree Value
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
if (root == null) {
return Integer.MIN_VALUE;
}
if (root.val > target) {
if (root.left != null) {
int left = closestValue(root.left, target);
if (Math.abs(left - target) < Math.abs(root.val - target)) {
return left;
}
}
} else {
if (root.right != null) {
int right = closestValue(root.right, target);
if (Math.abs(right - target) < Math.abs(root.val - target)) {
return right;
}
}
}
return root.val;
}
}