- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1602.java
34 lines (32 loc) · 1.05 KB
/
_1602.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
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.LinkedList;
importjava.util.Queue;
publicclass_1602 {
publicstaticclassSolution1 {
publicTreeNodefindNearestRightNode(TreeNoderoot, TreeNodeu) {
Queue<TreeNode> q = newLinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
intsize = q.size();
for (inti = 0; i < size; i++) {
TreeNodecurr = q.poll();
if (curr == u) {
if (i == size - 1) {
returnnull;
} else {
returnq.poll();
}
}
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
}
returnnull;
}
}
}