forked from acearth/LeetCodePractice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextRightPointerOfTree.java
55 lines (47 loc) · 1.4 KB
/
NextRightPointerOfTree.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
import base.TreeLinkNode;
import java.util.ArrayList;
public class NextRightPointerOfTree {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
root.next=null;
return;
}
ArrayList<TreeLinkNode> q = new ArrayList<>();
q.add(root);
while (true) {
ArrayList<TreeLinkNode> qq = new ArrayList<>();
while (q.size() > 0) {
TreeLinkNode tr = q.get(0);
q.remove(0);
if (tr.left != null) {
qq.add(tr.left);
}
if (tr.right != null) {
qq.add(tr.right);
}
}
for (int i = 0; i < qq.size() - 1; i++) {
qq.get(i).next = qq.get(i + 1);
}
if (qq.size() > 1) {
qq.get(qq.size() - 1).next = null;
}
if (qq.size() < 1) {
break;
}
q = qq;
}
}
public static void main(String[] args) {
NextRightPointerOfTree s = new NextRightPointerOfTree();
TreeLinkNode t1 = new TreeLinkNode(1);
TreeLinkNode t2 = new TreeLinkNode(2);
TreeLinkNode t3 = new TreeLinkNode(3);
t1.left = t2;
t1.right = t3;
s.connect(t1);
}
}