Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Last active September 3, 2017 17:12
Show Gist options
  • Select an option

  • Save cixuuz/a35d8dae151b77e7a82e0e9e3a78fbc8 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/a35d8dae151b77e7a82e0e9e3a78fbc8 to your computer and use it in GitHub Desktop.
[270. Closest Binary Search Tree Value] #leetcode
// O(log(n)) O(1)
class Solution {
public int closestValue(TreeNode root, double target) {
int a = root.val;
TreeNode kid = target < a ? root.left : root.right;
if (kid == null) return a;
int b = closestValue(kid, target);
return Math.abs(a - target) < Math.abs(b - target) ? a : b;
}
}
class Solution1 {
public int closestValue(TreeNode root, double target) {
int closest = root.val;
while (root != null) {
if (Math.abs(closest - target) >= Math.abs(root.val - target)) {
closest = root.val;
}
root = target < root.val ? root.left : root.right;
}
return closest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment