Created
July 17, 2019 19:06
-
-
Save sogwiz/f9ae040cb876a62fd89cf21dcd0f3d32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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