forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PopulatingNextRightPointersInEachNode.java
63 lines (51 loc) · 1.56 KB
/
PopulatingNextRightPointersInEachNode.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
51
52
53
54
55
56
57
58
59
60
61
62
63
// https://leetcode.com/problems/populating-next-right-pointers-in-each-node
// T: O(n)
// S: O(n)
import java.util.LinkedList;
import java.util.Queue;
public class PopulatingNextRightPointersInEachNode {
public static Node connect(Node root) {
if (root == null) return null;
final Queue<Node> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
Node previous = null;
while (!queue.isEmpty()) {
final Node current = queue.poll();
if (current == null) {
previous = null;
if (!queue.isEmpty()) queue.add(null);
continue;
}
if (previous != null) previous.next = current;
previous = current;
addChildrenToQueue(queue, current);
}
return root;
}
private static void addChildrenToQueue(Queue<Node> queue, Node root) {
if (root.left != null) queue.add(root.left);
if (root.right != null) queue.add(root.right);
}
private static class Node implements TreePrinter.PrintableNode {
public int val;
public Node left;
public Node right;
public Node next;
public Node(int val) {
this.val = val;
}
@Override
public TreePrinter.PrintableNode getLeft() {
return left;
}
@Override
public TreePrinter.PrintableNode getRight() {
return right;
}
@Override
public String getText() {
return val + "";
}
}
}