-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_116.java
More file actions
47 lines (42 loc) · 1.2 KB
/
Copy pathP_116.java
File metadata and controls
47 lines (42 loc) · 1.2 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
45
46
47
package leetcode.medium;
import java.util.ArrayDeque;
import java.util.Deque;
import utils.DataStructures.Node;
@SuppressWarnings("ConstantConditions")
public class P_116 {
public Node connect(Node root) {
if (root == null || root.left == null) {
return root;
}
root.left.next = root.right;
if (root.next != null) {
root.right.next = root.next.left;
}
connect(root.left);
connect(root.right);
return root;
}
public static Node connectBFS(Node root) {
final Deque<Node> q = new ArrayDeque<>();
if (root != null) {
q.offerLast(root);
}
while (!q.isEmpty()) {
Node prev = null;
for (int level = q.size(); level > 0; level--) {
final Node curr = q.removeFirst();
if (curr.left != null) {
q.offerLast(curr.left);
}
if (curr.right != null) {
q.offerLast(curr.right);
}
if (prev != null) {
prev.next = curr;
}
prev = curr;
}
}
return root;
}
}