forked from rpj911/LeetCode_algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPopulate2.java
71 lines (54 loc) · 1.98 KB
/
Populate2.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
64
65
66
67
68
69
70
71
package Algorithms;
import Algorithms.tree.TreeLinkNode;
public class Populate2 {
public static void main(String[] args) {
TreeLinkNode root = new TreeLinkNode(2);
root.left = new TreeLinkNode(1);
root.right = new TreeLinkNode(3);
root.left.left = new TreeLinkNode(0);
root.left.left.left = new TreeLinkNode(2);
root.left.right = new TreeLinkNode(7);
root.left.right.left = new TreeLinkNode(1);
root.left.right.right = new TreeLinkNode(0);
root.right.left = new TreeLinkNode(9);
root.right.right = new TreeLinkNode(1);
root.right.right.left = new TreeLinkNode(8);
root.right.right.right = new TreeLinkNode(8);
root.left.right.left.left = new TreeLinkNode(7);
Populate2 p2 = new Populate2();
p2.connect(root);
}
public void connect(TreeLinkNode root) {
if (root == null) {
return;
}
TreeLinkNode dummy0 = new TreeLinkNode(0);
TreeLinkNode dummy = dummy0;
if (root.left != null) {
dummy = connect_help(dummy, root.left);
}
if (root.right != null) {
dummy = connect_help(dummy, root.right);
}
if (dummy != dummy0) {
TreeLinkNode nextRoot = root.next;
while (nextRoot != null) {
if (nextRoot.left != null) {
dummy.next = nextRoot.left;
break;
} else if (nextRoot.right != null) {
dummy.next = nextRoot.right;
break;
}
nextRoot = nextRoot.next;
}
}
connect(root.left);
connect(root.right);
}
public TreeLinkNode connect_help(TreeLinkNode node1, TreeLinkNode node2) {
node1.next = node2;
node2.next = null;
return node2;
}
}