-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstTreeTest.d
94 lines (82 loc) · 1.59 KB
/
constTreeTest.d
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
import hurt.io.stdio;
class Node {
int value;
Node left, right, parent;
this(int value, Node parent) {
this.parent = parent;
this.value = value;
}
ConstIterator begin() {
return new ConstIterator(this);
}
int getValue() const {
return this.value;
}
void insert(int value) {
if(value > this.value && this.right !is null) {
this.right.insert(value);
} else if(value > this.value && this.right is null) {
this.right = new Node(value, this);
} else if(value < this.value && this.right !is null) {
this.left.insert(value);
} else if(value < this.value && this.right is null) {
this.left = new Node(value, this);
}
}
}
class ConstIterator {
Node ptr;
this(Node ptr) {
this.ptr = ptr;
}
const(Node) getValue() {
return this.ptr;
}
void increment() {
Node y;
if(null !is (y = this.ptr.right)) {
while(y.left !is null) {
y = y.left;
}
this.ptr = y;
} else {
y = this.ptr.parent;
while(y !is null && this.ptr is y.right) {
this.ptr = y;
y = y.parent;
}
this.ptr = y;
}
}
void decrement() {
Node y;
if(null !is (y = this.ptr.left)) {
while(y.right !is null) {
y = y.right;
}
this.ptr = y;
} else {
y = this.ptr.parent;
while(y !is null && this.ptr is y.left) {
this.ptr = y;
y = y.parent;
}
this.ptr = y;
}
}
bool isValid() const {
return this.ptr !is null;
}
}
void main() {
Node r = new Node(10, null);
for(int i = 0; i < 20; i+=2) {
r.insert(i);
}
ConstIterator it = r.begin();
while(it.isValid()) {
const(Node) n = it.getValue();
println(n.getValue());
it.increment();
}
}