Closest Binary Search Tree Value
class Solution {
double diff;
int result;
public int closestValue(TreeNode root, double target) {
diff = Double.MAX_VALUE;
result = 0;
helper(root, target);
return result;
}
private void helper(TreeNode root, double target) {
if (root == null) {
return;
}
double newDiff = Math.abs(root.val - target);
if (newDiff < diff) {
result = root.val;
diff = newDiff;
}
if (target < root.val) {
helper(root.left, target);
} else {
helper(root.right, target);
}
}
}
class Solution(object):
def closestValue(self, root, target):
r = root.val
while root:
if abs(root.val - target) < abs(r - target):
r = root.val
root = root.left if target < root.val else root.right
return r
最后更新于
这有帮助吗?