Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created April 13, 2016 19:00
Show Gist options
  • Select an option

  • Save cangoal/8a3c94ba1f03553c9686e23a9be28857 to your computer and use it in GitHub Desktop.

Select an option

Save cangoal/8a3c94ba1f03553c9686e23a9be28857 to your computer and use it in GitHub Desktop.
LeetCode - Closest Binary Search Tree Value
// Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
// Note:
// Given target value is a floating point.
// You are guaranteed to have only one unique value in the BST that is closest to the target.
// use successor and predecessor
public int closestValue(TreeNode root, double target) {
TreeNode successor = null, predecessor = null;
while(root != null){
if(root.val > target){
successor = root;
root = root.left;
} else if(root.val < target) {
predecessor = root;
root = root.right;
} else{
return root.val;
}
}
if(successor == null && predecessor == null) return -1;
if(successor == null) return predecessor.val;
if(predecessor == null) return successor.val;
if(Math.abs(target - successor.val) < Math.abs(target - predecessor.val)){
return successor.val;
} else {
return predecessor.val;
}
}
// normal way
public int closestValue(TreeNode root, double target) {
if(root == null) return -1;
int res = root.val;
while(root != null){
if(Math.abs(root.val - target) < Math.abs(res - target)){
res = root.val;
}
root = root.val > target ? root.left : root.right;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment