Closest Binary Search Tree Value
Input: root = [4,2,5,1,3], target = 3.714286
4
/ \
2 5
/ \
1 3
Output: 4/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int closestValue(TreeNode root, double target) {
if(root == null )
return -1;
TreeNode floor = getFloor(root,(int)target);
TreeNode ceiling = getCeiling(root,(int)target+1);
if(!(floor == null && ceiling==null)){
if(floor == null || ceiling!=null && Math.abs(target-ceiling.val) < Math.abs(target-floor.val)){
return ceiling.val;
}else{
return floor.val;
}
}
return -1;
}
public TreeNode getFloor(TreeNode root, int target){
if(root == null)
return null;
if(root.val == target)
return root;
else if(root.val > target){
return getFloor(root.left,target);
}else{
TreeNode n = getFloor(root.right,target);
return n==null? root:n;
}
}
public TreeNode getCeiling(TreeNode root, int target){
if(root == null)
return null;
if(root.val == target)
return root;
else if(root.val < target){
return getCeiling(root.right,target);
}else{
TreeNode n = getCeiling(root.left,target);
return n==null? root:n;
}
}
}Last updated