public class Solution {
public int closestValue(TreeNode root, double target) {
if(root.val == target) {
return root.val;
} else if(target > root.val) {
// if target is larger than root,
// the answer can only be
// 1. root itself
// 2. inside the right sub tree
return root.right == null ? root.val : (Math.abs(target-root.val) <
Math.abs(target-closestValue(root.right, target))
? root.val: closestValue(root.right, target));
} else {
// if target is smaller than root,
// the answer can only be
// 1. root itself
// 2. inside the left sub tree.
return root.left == null ? root.val : (Math.abs(target-root.val) <
Math.abs(target-closestValue(root.left, target))
? root.val: closestValue(root.left, target));
}
}
}
/**
public class Solution { public int closestValue(TreeNode root, double target) { if(root.val == target) { return root.val; } else if(target > root.val) { // if target is larger than root, // the answer can only be // 1. root itself // 2. inside the right sub tree return root.right == null ? root.val : (Math.abs(target-root.val) < Math.abs(target-closestValue(root.right, target)) ? root.val: closestValue(root.right, target)); } else { // if target is smaller than root, // the answer can only be // 1. root itself // 2. inside the left sub tree. return root.left == null ? root.val : (Math.abs(target-root.val) < Math.abs(target-closestValue(root.left, target)) ? root.val: closestValue(root.left, target)); } } }