Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created April 27, 2019 19:14
Show Gist options
  • Save shixiaoyu/afb93a8200f80695c9c5498d0b1e9dd0 to your computer and use it in GitHub Desktop.
Save shixiaoyu/afb93a8200f80695c9c5498d0b1e9dd0 to your computer and use it in GitHub Desktop.
private double curMinDelta = Double.MAX_VALUE;
private int smallestValue = 0;
public int closestValue(TreeNode root, double target) {
this.searchMin(root, target);
return this.smallestValue;
}
private void searchMin(TreeNode root, double target) {
if (root == null) {
return;
}
if (target == root.val) {
this.smallestValue = root.val;
return;
}
double delta = Math.abs(target - root.val);
if (delta < this.curMinDelta) {
smallestValue = root.val;
this.curMinDelta = delta;
}
if (target < root.val) {
this.searchMin(root.left, target);
} else {
this.searchMin(root.right, target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment