-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path272-nearestKinBST.java
More file actions
44 lines (43 loc) · 1.25 KB
/
272-nearestKinBST.java
File metadata and controls
44 lines (43 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class Solution_272 {
LinkedList<Integer> res = new LinkedList<>();
TreeNode pre;
boolean nearest = false;
int count = 0;
public List<Integer> closestKValues(TreeNode root, double target, int k) {
if(root == null || k==0) return res;
inOrder(root, k, target);
int l=0, r=res.size()-1;
while(r-l+1 > k) {
if(Math.abs(res.peekFirst()-target) > Math.abs(res.peekLast()-target)) {
res.pollFirst();l++;
} else {
res.pollLast();r--;
}
}
return res;
}
private void inOrder(TreeNode root, int k, double target) {
if(root == null) return;
inOrder(root.left, k, target);
if(!nearest && pre!=null && pre.val <= target && root.val >= target) {
nearest = true;
if(res.size() > k) {
for(int i=0; i<res.size() - k; i++) res.pollLast();
}
}
res.add(root.val);
if(nearest) count++;
if(count == k) return;
inOrder(root.right, k, target);
}
}