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;
    }
}

你可能感兴趣的:(270. Closest Binary Search Tree Value)