-
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
package com.fishercoder.solutions.secondthousand;
import com.fishercoder.common.classes.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
public class _1602 {
public static class Solution1 {
public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode curr = q.poll();
if (curr == u) {
if (i == size - 1) {
return null;
} else {
return q.poll();
}
}
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
}
return null;
}
}
}