-
Notifications
You must be signed in to change notification settings - Fork 0
/
PopulatingNext.java
59 lines (57 loc) · 1.53 KB
/
PopulatingNext.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
public class PopulatingNext {
class Node {
public int val;
public Node left;
public Node right;
public Node next;
}
// BFS
public Node connect(Node root) {
if (root == null) return root;
Node head = root;
while (head != null) {
Node prev = null;
Node nextHead = null;
while (head != null) {
if (head.left != null) {
if (prev != null) {
prev.next = head.left;
}
prev = head.left;
if (nextHead == null) {
nextHead = head.left;
}
}
if (head.right != null) {
if (prev != null) {
prev.next = head.right;
}
prev = head.right;
if (nextHead == null) {
nextHead = head.right;
}
}
head = head.next;
}
head = nextHead;
}
return root;
}
// DFS
public Node connect1(Node root) {
List<Node> tails = new ArrayList<>();
dfs(tails, root, 0);
return root;
}
private void dfs(List<Node> tails, Node root, int level) {
if (root == null) return;
if (tails.size() == level) {
tails.add(root);
} else {
tails.get(level).next = root;
tails.set(level, root);
}
dfs(tails, root.left, level + 1);
dfs(tails, root.right, level + 1);
}
}