-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode_2476.java
68 lines (57 loc) · 1.88 KB
/
LeetCode_2476.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayList;
import java.util.List;
public class LeetCode_2476 {
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<List<Integer>> closestNodes(TreeNode root, List<Integer> queries) {
List<List<Integer>> list = new ArrayList<>();
for (Integer query : queries) {
List<Integer> temp = new ArrayList<>();
temp.add(find_min(root, query));
temp.add(find_max(root, query));
list.add(temp);
}
return list;
}
public Integer find_min(TreeNode node, Integer count) {
if (node == null) {
return -1;
}
if (node.val > count) {
return find_min(node.left, count);
} else if (node.val < count) {
Integer minInRightSubtree = find_min(node.right, count);
return minInRightSubtree != -1 ? Math.max(node.val, minInRightSubtree) : node.val;
} else {
return node.val;
}
}
public Integer find_max(TreeNode node, Integer count) {
if (node == null) {
return -1;
}
if (node.val < count) {
return find_max(node.right, count);
} else if (node.val > count) {
Integer maxInLeftSubtree = find_max(node.left, count);
return maxInLeftSubtree != -1 ? Math.min(node.val, maxInLeftSubtree) : node.val;
} else {
return node.val;
}
}
}
}