-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node.java
100 lines (82 loc) · 1.85 KB
/
Node.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.util.ArrayList;
public class Node {
Node parent;
Node rightChild;
Node leftChild;
public Node() {
parent = null;
rightChild = null;
leftChild = null;
}
public void emplaceRight(Node rightChild) {
if(rightChild == null) {
this.rightChild = rightChild;
rightChild.parent = this;
}
else {
emplaceRight(rightChild);
}
}
public void removeRight() {
if(rightChild == null) {
this.parent.rightChild = null;
this.parent = null;
}
else {
removeRight();
}
}
public Node randomizeTree() {
ArrayList<Node> arrayList = new ArrayList<Node>();
this.inOrderAddToArrayList(arrayList);
long seed = System.nanoTime();
Collections.shuffle(arrayList, new Random(seed));
for(int i = 0; i < arrayList.size(); i++) {
arrayList.get(i).parent = null;
arrayList.get(i).rightChild = null;
arrayList.get(i).leftChild = null;
}
int rootIndex = Math.random.nextInt(arrayList.size());
Node newRoot = arrayList.get(rootIndex);
for(int i = rootIndex - 1; i >= 0; i--) {
newRoot.emplaceRight(arrayList.get(i));
}
for(int i = rootIndex + 1; i < arrayList.size(); i++) {
newRoot.emplaceLeft(arrayList.get(i));
}
return newRoot;
}
private void inOrderAddToArrayList(ArrayList<Node> arrayList) {
if(this.leftChild == null) {
arrayList.add(this);
}
else {
this.inOrderAddToArrayList(arrayList);
}
if(this.rightChild == null) {
this.inOrderAddToArrayList(arrayList);
}
}
public boolean doTheHokeyPokey() {
// TODO: the hokey pokey
return true;
}
public void emplaceLeft(Node leftChild) {
if(this.leftChild == null) {
this.leftChild = leftChild;
leftChild.parent = this;
}
else {
emplaceLeft(leftChild);
}
}
public void removeLeft() {
if(this.leftChild == null) {
this.parent.leftChild = null;
this.parent = null;
}
else {
removeLeft();
}
}
}