This repository has been archived by the owner on Nov 24, 2020. It is now read-only.
forked from ancientlore/go-avltree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
365 lines (306 loc) · 7.97 KB
/
tree.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
An AVL tree (Adel'son-Vel'skii & Landis) is a binary search
tree in which the heights of the left and right subtrees
of the root differ by at most one and in which the left
and right subtrees are again AVL trees.
With each node of an AVL tree is associated a balance factor
that is Left High, Equal, or Right High according,
respectively, as the left subtree has height greater than,
equal to, or less than that of the right subtree.
The AVL tree is, in practice, balanced quite well. It can
(at the worst case) become skewed to the left or right,
but never so much that it becomes inefficient. The
balancing is done as items are added or deleted.
This version is enhanced to allow "indexing" of values in the
tree; however, the indexes are not stable as the tree could be
resorted as items are added or removed.
It is safe to iterate or search a tree from multiple threads
provided that no threads are modifying the tree.
See also: Robert L. Kruse, Data Structures and Program Design, 2nd Ed., Prentice-Hall
*/
package avltree
import (
"math"
)
// tree options
const (
AllowDuplicates = 1
)
// Definition of a comparison function
type CompareFunc func(v1 interface{}, v2 interface{}) int
// Iterate function
type IterateFunc func(v interface{})
// Tree object
type Tree struct {
// root of the tree
root *treeNode
// compare function
compare CompareFunc
// options controlling behavior
treeFlags byte
}
// Initialize or reset a Tree
func (t *Tree) Init(c CompareFunc, flags byte) *Tree {
t.compare = c
t.root = nil
t.treeFlags = flags
return t
}
// Return an initialized tree
func New(c CompareFunc, flags byte) *Tree { return new(Tree).Init(c, flags) }
// Clear removes all elements from the tree, keeping the
// current options and compare function
func (t *Tree) Clear() { t.Init(t.compare, t.treeFlags) }
// calcHeightData contains information needed to compute the
// height of the tree
type calcHeightData struct {
currentHeight int
maxHeight int
}
// calcHeight executes recursively to determine the height
// (number of levels) in the tree.
func (d *calcHeightData) calcHeight(node *treeNode) {
d.currentHeight++
if node.left != nil {
d.calcHeight(node.left)
}
if node.right != nil {
d.calcHeight(node.right)
}
if d.currentHeight > d.maxHeight {
d.maxHeight = d.currentHeight
}
d.currentHeight--
}
// Height returns the "height" of the tree, meaning the
// number of levels.
func (t *Tree) Height() int {
d := &calcHeightData{0, 0}
if t.root != nil {
d.calcHeight(t.root)
}
return d.maxHeight
}
// Len returns the number of elements in the tree
func (t *Tree) Len() int {
if t.root != nil {
return t.root.size
}
return 0
}
// Cap returns the capacity of the tree; that is, the
// maximum elements the tree can hold with at the
// current height. This is only useful as a measure
// of how skewed the tree is.
func (t *Tree) Cap() int {
var count, i int
count = 0
maxHeight := t.Height()
for i = 0; i < maxHeight; i++ {
count += int(math.Pow(2, float64(i)))
}
return count
}
// indexer recursively scans the tree to find the node
// at the given position
func indexer(node *treeNode, index int) *treeNode {
if index < node.leftSize() {
return indexer(node.left, index)
} else if index == node.leftSize() {
return node
} else if node.right != nil {
return indexer(node.right, index-(node.leftSize()+1))
}
return nil
}
// At returns the value at the given index
func (t *Tree) At(index int) interface{} {
if t.root != nil && index < t.root.size && index >= 0 {
node := indexer(t.root, index)
if node != nil {
return node.value
}
}
return nil
}
// findData is used when searching the tree
type findData struct {
lookingFor interface{}
compare CompareFunc
}
// finder recursively scans the tree to find the node with the
// value we're looking for
func (d *findData) finder(node *treeNode) *treeNode {
if node != nil {
code := d.compare(d.lookingFor, node.value)
if code < 0 {
return d.finder(node.left)
} else if code > 0 {
return d.finder(node.right)
}
return node
}
return nil
}
// findpather recursively scans the tree to find the node with the value we're
// looking for, writing each step of the path to a channel.
func (d *findData) findpather(node *treeNode, ch chan<- *treeNode) {
if node == nil || ch == nil {
return
}
code := d.compare(d.lookingFor, node.value)
ch <- node
if code < 0 {
d.findpather(node.left, ch)
} else if code > 0 {
d.findpather(node.right, ch)
} else {
close(ch)
}
}
// Find returns the element where the comparison function matches
// the node's value and the given key value
func (t *Tree) Find(key interface{}) interface{} {
if key != nil && t.root != nil {
d := &findData{key, t.compare}
node := d.finder(t.root)
if node != nil {
return node.value
}
}
return nil
}
// FindPath returns a slice of elements showing the path in the tree to find
// the value.
func (t *Tree) FindPath(key interface{}) []interface{} {
values := []interface{}{}
if key != nil && t.root != nil {
d := &findData{key, t.compare}
ch := make(chan *treeNode)
go d.findpather(t.root, ch)
for node := range ch {
values = append(values, node.value)
}
}
return values
}
type iterRangeData struct {
min interface{}
max interface{}
compare CompareFunc
}
// iterranger recursively scans the tree to find nodes within a range and
// writes them to a channel.
func (d *iterRangeData) iterranger(node *treeNode, ch chan<- interface{}, isRoot bool) {
if node == nil {
return
}
minCode := d.compare(d.min, node.value)
maxCode := d.compare(d.max, node.value)
if minCode < 0 {
d.iterranger(node.left, ch, false)
}
if minCode <= 0 && maxCode >= 0 {
ch <- node.value
}
if maxCode > 0 {
d.iterranger(node.right, ch, false)
}
if isRoot {
close(ch)
}
}
// IterRange returns a channel you can iterate through to on items between a
// min and a max value (min <= x <= max).
// min and max are optional, defaulting to FindMin() and FindMax().
func (t *Tree) IterRange(min, max interface{}) <-chan interface{} {
if min == nil && max == nil {
return t.Iter()
}
if min == nil {
min = t.FindMin()
}
if max == nil {
max = t.FindMax()
}
values := make(chan interface{})
if t.root != nil {
d := &iterRangeData{min, max, t.compare}
go d.iterranger(t.root, values, true)
} else {
close(values)
}
return values
}
func findmax(node *treeNode) *treeNode {
if node.right == nil {
return node
}
return findmax(node.right)
}
// FindMax returns the rightmost (maximum) item from the tree.
func (t *Tree) FindMax() interface{} {
if t.root == nil {
return nil
}
return findmax(t.root).value
}
func findmin(node *treeNode) *treeNode {
if node.left == nil {
return node
}
return findmin(node.left)
}
// FindMin returns the leftmost (minimum) item from the tree.
func (t *Tree) FindMin() interface{} {
if t.root == nil {
return nil
}
return findmin(t.root).value
}
// iterData is used when iterating the tree
type iterData struct {
iter IterateFunc
}
// iterate recursively traverses the tree and executes
// the iteration function
func (d *iterData) iterate(node *treeNode) {
if node.left != nil {
d.iterate(node.left)
}
d.iter(node.value)
if node.right != nil {
d.iterate(node.right)
}
}
// Do calls function f for each element of the tree, in order.
// The function should not change the structure of the tree underfoot.
func (t *Tree) Do(f IterateFunc) {
if f != nil && t.root != nil {
d := &iterData{f}
d.iterate(t.root)
}
}
// chanIterate should be used as a goroutine to produce all the values
// in the tree.
func (t *Tree) chanIterate(c chan<- interface{}) {
t.Do(func(v interface{}) { c <- v })
close(c)
}
// Iter returns a channel you can read through to fetch all the items
func (t *Tree) Iter() <-chan interface{} {
c := make(chan interface{})
go t.chanIterate(c)
return c
}
// Data returns all the elements as a slice.
func (t *Tree) Data() []interface{} {
arr := make([]interface{}, t.Len())
var i int
i = 0
t.Do(func(v interface{}) {
arr[i] = v
i++
})
return arr
}