java 最近的二进制搜索树值(270. leetcode)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 最近的二进制搜索树值(270. leetcode)相关的知识,希望对你有一定的参考价值。
// recursive
public class Solution {
int goal;
double min = Double.MAX_VALUE;
public int closestValue(TreeNode root, double target) {
helper(root, target);
return goal;
}
public void helper(TreeNode root, double target){
if(root==null)
return;
if(Math.abs(root.val - target) < min){
min = Math.abs(root.val-target);
goal = root.val;
}
if(target < root.val){
helper(root.left, target);
}else{
helper(root.right, target);
}
}
}
// iterative
public int closestValue(TreeNode root, double target) {
double min=Double.MAX_VALUE;
int result = root.val;
while(root!=null){
if(target>root.val){
double diff = Math.abs(root.val-target);
if(diff<min){
min = Math.min(min, diff);
result = root.val;
}
root = root.right;
}else if(target<root.val){
double diff = Math.abs(root.val-target);
if(diff<min){
min = Math.min(min, diff);
result = root.val;
}
root = root.left;
}else{
return root.val;
}
}
return result;
}
以上是关于java 最近的二进制搜索树值(270. leetcode)的主要内容,如果未能解决你的问题,请参考以下文章
java 270.最近的二进制搜索树值(#)。java
java 270.最近的二进制搜索树值(#)。java
java 最近的二进制搜索树值(270. leetcode)
java 272.最近的二进制搜索树值II(#)。java
java 272.最近的二进制搜索树值II(#)。java
java 272.最近的二进制搜索树值II(#)。java