-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.java
113 lines (83 loc) · 2.89 KB
/
BinaryTree.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
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.concurrent.atomic.AtomicReferenceArray;
public class BinaryTree {
AtomicReferenceArray tree;
static int nonLeafNodes;
static int levels;
static int size;
int minValue(){
if (tree.get(0).equals(Integer.MAX_VALUE)){
return Integer.MAX_VALUE;
}
return (int) tree.get(0) >> 16;
}
public BinaryTree(int n){
int closest2Power = (int)Math.ceil(Math.log(n) / Math.log(2));
levels = closest2Power;
int leafNodes = (int) Math.pow(2, closest2Power);
nonLeafNodes = leafNodes - 1;
size = ((2 * leafNodes) - 1) - leafNodes + n;
tree = new AtomicReferenceArray(size);
for (int i=0; i < size; i++){
tree.set(i, Integer.MAX_VALUE);
}
// System.out.println(size);
}
boolean insertIntoTree(int processID, int val){
int slot = nonLeafNodes + processID;
boolean retValue = true;
if (!tree.get(slot).equals(Integer.MAX_VALUE)) {
retValue = false;
}
tree.set(slot,val);
// bubble Up
int i =0;
while (i != levels) {
int buddyIndex = slot % 2 == 0 ? slot - 1 : slot + 1;
int minValue = val;
if (buddyIndex < size) {
minValue = Math.min((Integer) tree.get(slot), (Integer) tree.get(buddyIndex));
}
int parentIndex = (int) Math.floor((slot - 1) / 2);
Object o = tree.get(parentIndex);
if (!tree.compareAndSet(parentIndex, o, minValue))
tree.compareAndSet(parentIndex, o, minValue);
i++;
slot = parentIndex;
}
return retValue;
}
boolean deleteFromTree(int processID){
int slot = nonLeafNodes + processID;
boolean retValue = true;
if (tree.get(slot).equals(Integer.MAX_VALUE)) {
retValue = false;
}
tree.set(slot,Integer.MAX_VALUE);
// printTree();
// bubble Up
int i =0;
while (i != levels) {
int buddyIndex = slot % 2 == 0 ? slot - 1 : slot + 1;
int minValue = Integer.MAX_VALUE;
if (buddyIndex < size) {
minValue = Math.min((Integer) tree.get(slot), (Integer) tree.get(buddyIndex));
}
int parentIndex = (int) Math.floor((slot - 1) / 2);
Object o = tree.get(parentIndex);
if (!tree.compareAndSet(parentIndex, o, minValue))
tree.compareAndSet(parentIndex, o, minValue);
i++;
slot = parentIndex;
}
// printTree();
return retValue;
}
void printTree()
{
System.out.println("Array representation of Tree:");
for (int i = nonLeafNodes; i < tree.length(); ++i){
int value = (int) tree.get(i) & 0xffff0000;
System.out.print(value + " ");
}
}
}