idea : inorder traversal get sorted list+ leetcode 658 (binary search + sliding window)
/**
* 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);
}
}