-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution117.java
More file actions
45 lines (40 loc) · 1010 Bytes
/
Copy pathSolution117.java
File metadata and controls
45 lines (40 loc) · 1010 Bytes
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
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution117 {
public Node connect(Node root) {
bfs(root);
return root;
}
public void bfs(Node root) {
Queue<Node> queue = new ArrayDeque<>();
if (root != null) queue.offer(root);
while(!queue.isEmpty()) {
int n = queue.size();
for (int i = 0; i < n; i++) {
Node t = queue.poll();
if (i == n - 1) t.next = null;
else t.next = queue.peek();
if (t.left != null) queue.offer(t.left);
if (t.right != null) queue.offer(t.right);
}
}
return;
}
}