Thinking process
Using binary search in the tree, until the root == null
Mistakes
- minDiff should be double
- when to use if and if, when to use if , else if
- when diff equals to MAX_VALUE?
- when diff is larger than MAX_VALUE? long?
public class Solution {
public int closestValue(TreeNode root, double target) {
int result = root.val;
while (root != null) {
if (root.val == target) {
return root.val;
}
if (Math.abs(root.val - target) < Math.abs(result - target)) {
result = root.val;
}
if (root.val > target) {
root = root.left;
} else if (root.val < target) {
root = root.right;
}
}
return result;
}
}