Repository navigation
Expand file tree
/
Copy pathPopulatingNextRightPointers.java
More file actions
55 lines (55 loc) · 1.64 KB
/
Copy pathPopulatingNextRightPointers.java
File metadata and controls
55 lines (55 loc) · 1.64 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
48
49
50
51
52
53
54
55
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class PopulatingNextRightPointers {
public void connect(TreeLinkNode root) {
if (root == null)
return;
TreeLinkNode node = root;
root.next = null;
TreeLinkNode p1 = null;
while (true) {
p1 = null;
// find the head of the next level
while (p1 == null && node != null) {
if (node.left != null)
p1 = node.left;
else if (node.right != null)
p1 = node.right;
else
node = node.next;
}
TreeLinkNode newNode = p1; // the next node
// exit when there is no head of the next level
if (node == null)
break;
// prepare
if (p1 == node.left) {
if (node.right != null) {
p1.next = node.right;
p1 = p1.next;
}
}
node = node.next;
// connect everthing in the next level
while (node != null) {
if (node.left != null) {
p1.next = node.left;
p1 = p1.next;
}
if (node.right != null) {
p1.next = node.right;
p1 = p1.next;
}
node = node.next;
}
p1.next = null;
node = newNode;
}
}
}