270. Closest Binary Search Tree Value

Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Note:

  • Given target value is a floating point.
  • You are guaranteed to have only one unique value in the BST that is closest to the target.

一刷
题解:
方法1,递归
递归的原理是,如果target<root.val, 那么最接近值只会是root或者存在于root的左子树。

/**
 * 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 = a < target? root.right: root.left;
        if(kid == null) return a;
        int b = closestValue(kid, target);
        if(Math.abs(a-target)<Math.abs(b-target)) return a;
        else return b;
    }
}

方法二,iteration

/**
 * 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 closest = root.val;
        while(root!=null){
            if(Math.abs(closest-target) >= Math.abs(root.val - target))
                closest = root.val;
            root = target < root.val? root.left: root.right;
        }
        return closest;
    }
}

二刷
同上

/**
 * 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) {
        if((double)root.val == target) return root.val;
        if(target<root.val && root.left == null) return root.val;
        if(target>root.val && root.right == null) return root.val;
        if(target<root.val){
            int left = closestValue(root.left, target);
            if(Math.abs(root.val - target)< Math.abs(left - target))
                return root.val;
            else return left;
        }
        if(target > root.val){
            int right = closestValue(root.right, target);
            if(Math.abs(root.val - target)< Math.abs(right - target))
                return root.val;
            else return right;
        }
        return 0;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容