-
Notifications
You must be signed in to change notification settings - Fork 9
/
PopulatingNextRightPointersInEachNode2.java
50 lines (48 loc) · 1.69 KB
/
PopulatingNextRightPointersInEachNode2.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
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class PopulatingNextRightPointersInEachNode2 {
public void connect(TreeLinkNode root) {
if (root == null) return;
Deque<TreeLinkNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
TreeLinkNode prev = null;
for (int i = 0; i < size; i++) {
TreeLinkNode node = queue.poll();
if (prev != null) prev.next = node;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
prev = node;
}
}
}
}
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode nextLevelStart = root;
TreeLinkNode previous = null;
while (nextLevelStart != null) {
TreeLinkNode parent = nextLevelStart;
nextLevelStart = null;
previous = null;
while (parent != null) {
if (nextLevelStart == null) nextLevelStart = parent.left;
if (nextLevelStart == null) nextLevelStart = parent.right;
previous = connectNodes(previous, parent.left);
previous = connectNodes(previous, parent.right);
parent = parent.next;
}
}
}
public TreeLinkNode connectNodes(TreeLinkNode previous, TreeLinkNode next) {
if (previous != null) previous.next = next;
return next == null ? previous : next;
}
}