# 272. Closest Binary Search Tree Value II

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MjnqYHwOovG5l0c1oXQ%2F-Mjnrtw9KHfZ-B0aP7MN%2Fimage.png?alt=media\&token=aaf85822-f6ef-4917-80a5-95b350855f38)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MjnqYHwOovG5l0c1oXQ%2F-Mjns1W893uznGff4pX4%2Fimage.png?alt=media\&token=4c5b9d54-6f0e-4fb3-8070-d2b603b9feba)

## idea : inorder traversal get sorted list+ leetcode 658 (binary search + sliding window)

time: O(n + logn + k) = O(n)

space: O(n)

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> res = new ArrayList<>();
        
        List<Integer> list = new ArrayList<>();
        inorder(root, list);
        
        int left = 0;
        int right = list.size() - k;
        while (left < right) {
            int mid = left + (right - left)/2;
            if (target - list.get(mid) > list.get(mid+k) - target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        for (int i = left; i < left + k; i++) {
            res.add(list.get(i));
        }
        return res;
    }
    private void inorder(TreeNode root, List<Integer> list) {
        if (root == null) return;
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}


```

**Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)? ...oh, give up first.
