class Solution {
public int closestValue(TreeNode root, double target) {
int res = root.val;
while (root != null) {
if (Math.abs(target - root.val) < Math.abs(target - res)) {
res = root.val;
}
if (root.val > target) root = root.left;
else root = root.right;
}
return res;
}
}
well, I thought about in-order traversal and the double kinda confused me for a while, but the solution seems so easy by following the logic to judge whether it's smaller and righter and go to one branch.
And also, comparing int with double is valid, our algorithm will cast int to double before comparison.
But using == or != is not valid.
Easy version.
well, I thought about in-order traversal and the double kinda confused me for a while, but the solution seems so easy by following the logic to judge whether it's smaller and righter and go to one branch. And also, comparing int with double is valid, our algorithm will cast int to double before comparison. But using == or != is not valid.