Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
- Given target value is a floating point.
- You may assume k is always valid, that is: k ≤ total nodes.
- You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Example:
Input: root = [4,2,5,1,3], target = 3.714286, and k = 2 4 / \ 2 5 / \ 1 3 Output: [4,3]
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
题意
和之前一样,不过这次要找的是最接近的k个值。
Solution1:
1. Based on BST's attributes, if we traversal BST inorder, each node will be in acsending order
2. we choose a data structure which can help operate on both sides(LinkedList or Deque), maintaining a K size sliding window
once there is a new item,
we check diff (1) next item vs target
(2) leftMost item vs target
code
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 11 /* 12 Time Complexity: O(n) 13 Space Complexity:O(k) 14 */ 15 class Solution { 16 // choose a data structure which can do operations on both sides 17 LinkedList<Integer> result = new LinkedList<>(); 18 19 public List<Integer> closestKValues(TreeNode root, double target, int k) { 20 // corner case 21 if (root == null) {return null;} 22 // inorder traversal 23 closestKValues(root.left, target, k); 24 25 if (result.size() < k) { 26 result.add(root.val); 27 // maintain a K size sliding window such that items are closest to the target 28 } else if(result.size() == k) { 29 if (Math.abs(result.getFirst() - target) > (Math.abs(root.val - target))) { 30 result.removeFirst(); 31 result.addLast(root.val); 32 } 33 } 34 // inorder traversal 35 closestKValues(root.right, target, k); 36 return result; 37 } 38 }