Skip to content

Instantly share code, notes, and snippets.

@sogwiz
Created July 17, 2019 19:06
Show Gist options
  • Save sogwiz/f9ae040cb876a62fd89cf21dcd0f3d32 to your computer and use it in GitHub Desktop.
Save sogwiz/f9ae040cb876a62fd89cf21dcd0f3d32 to your computer and use it in GitHub Desktop.
package com.learning.leet.tree;
/**
* Created by sargonbenjamin on 7/17/19.
* https://leetcode.com/problems/closest-binary-search-tree-value/
*/
public class ClosestBSTValue {
TreeNode minNode = null;
double minDelta = Double.MAX_VALUE;
public int closestValue(TreeNode root, double target) {
helper(root, target);
return minNode ==null ? 0: minNode.val;
}
public void helper(TreeNode curr, double target){
if(curr==null)return;
if(curr.val==target){
minNode = curr;
return;
}
double delta = Math.abs((double)curr.val-target);
if(delta<minDelta){
minDelta = delta;
minNode = curr;
}
if(target < curr.val){
helper(curr.left, target);
}else{
helper(curr.right, target);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment