270. Closest Binary Search Tree Value

Solution1:二分查找 Recursive写法

思路:
Time Complexity: O(logN) Space Complexity: O(N) 递归缓存

Solution2:二分查找 Iterative写法

思路:
Time Complexity: O(logN) Space Complexity: O(1)

Solution1 Code:

class Solution1 {
    public int closestValue(TreeNode root, double target) {
        TreeNode next = target < root.val ? root.left : root.right;
        if(next == null) return root.val;
        int val_found = closestValue(next, target);
        return Math.abs(val_found - target) < Math.abs(root.val - target) ? val_found : root.val;
    }
}

Solution2 Code:

class Solution2 {
    public int closestValue(TreeNode root, double target) {
        if(root == null) return 0;
        
        int closest = root.val;
        TreeNode cur = root;
        while(cur != null) {
            if(Math.abs(cur.val - target) < Math.abs(closest - target)) closest = cur.val;
            cur = target < cur.val ? cur.left : cur.right;
        }
        return closest;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容