java 270.最近的二进制搜索树值(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 270.最近的二进制搜索树值(#)。java相关的知识,希望对你有一定的参考价值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int closestValue(TreeNode root, double target) {
        int res = root.val;
        double diff = Double.MAX_VALUE;
        while(root != null) {
            if(root.val == target) return root.val;
            double curr = Math.abs(root.val - target);
            if(curr < diff) {
                res = root.val;
                diff = curr;
            }
            if(root.val > target) root = root.left;
            else root = root.right;
        }
        return res;
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public int closestValue(TreeNode root, double target) {
        int a = root.val;
        TreeNode kid = target < a ? root.left : root.right;
        if (kid == null) return a;
        int b = closestValue(kid, target);
        return Math.abs(a - target) < Math.abs(b - target) ? a : b;
    }
}

以上是关于java 270.最近的二进制搜索树值(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 270.最近的二进制搜索树值(#)。java

java 270.最近的二进制搜索树值(#)。java

java 最近的二进制搜索树值(270. leetcode)

java 272.最近的二进制搜索树值II(#)。java

java 272.最近的二进制搜索树值II(#)。java

java 272.最近的二进制搜索树值II(#)。java