-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathitree.go
362 lines (308 loc) · 8.46 KB
/
itree.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
// Package interval provides an implementation of an interval tree built using
// an augmented AVL tree. An interval tree stores values associated with
// intervals, and can efficiently determine which intervals overlap with
// others. All intervals must have a unique starting position. It supports the
// following operations, where 'n' is the number of
// intervals in the tree:
//
// - Put: add an interval to the tree. Complexity: O(lg n).
//
// - Get: find an interval with a given starting position. Complexity O(lg n).
//
// - Overlaps: find all intervals that overlap with a given interval. Complexity:
// O(lg n + m), where 'm' is the size of the result (number of overlapping
// intervals found).
//
// - Remove: remove the interval at a given position. Complexity: O(lg n).
package interval
import (
"fmt"
"github.com/zyedidia/generic"
"golang.org/x/exp/constraints"
)
type KV[I constraints.Ordered, V any] struct {
Low, High I
Val V
}
func newKV[I constraints.Ordered, V any](n *node[I, V]) KV[I, V] {
return KV[I, V]{
Low: n.key.low,
High: n.key.high,
Val: n.value,
}
}
// intrvl represents an interval over [low, high).
type intrvl[I constraints.Ordered] struct {
low, high I
}
func newIntrvl[I constraints.Ordered](low, high I) intrvl[I] {
if low > high {
panic(fmt.Sprintf("low cannot be greater than high: %v > %v", low, high))
}
return intrvl[I]{low, high}
}
func overlaps[I constraints.Ordered](i1 intrvl[I], i2 intrvl[I]) bool {
return i1.low < i2.high && i1.high > i2.low
}
// Tree implements an interval tree. All intervals must have unique starting
// positions. Every low bound if an interval is inclusive, while high is
// exclusive.
type Tree[I constraints.Ordered, V any] struct {
root *node[I, V]
}
// New returns an empty interval tree.
func New[I constraints.Ordered, V any]() *Tree[I, V] {
return &Tree[I, V]{}
}
// Add associates the interval [low, high) with value.
//
// If an interval starting at low already exists in t, this method doesn't
// perform any change of the tree, but returns the conflicting interval.
func (t *Tree[I, V]) Add(low, high I, value V) (KV[I, V], bool) {
newRoot, kv, ok := t.root.insert(newIntrvl(low, high), value, false)
t.root = newRoot
return kv, ok
}
// Put associates the interval [low, high) with value.
//
// If an interval starting at low already exists, this method will replace it.
// In such a case the conflicting (replaced) interval is returned.
func (t *Tree[I, V]) Put(low, high I, value V) (KV[I, V], bool) {
newRoot, kv, ok := t.root.insert(newIntrvl(low, high), value, true)
t.root = newRoot
return kv, ok
}
// Overlaps returns all values that overlap with the given range. List returned
// is sorted by low positions of intervals.
func (t *Tree[I, V]) Overlaps(low, high I) []KV[I, V] {
return t.root.overlaps(newIntrvl(low, high), nil)
}
// Remove deletes the interval starting at low. The removed interval is
// returned. If no such interval existed in a tree, the returned value is false.
func (t *Tree[I, V]) Remove(low I) (KV[I, V], bool) {
newRoot, kv, ok := t.root.remove(low)
t.root = newRoot
return kv, ok
}
// Get returns the interval and value associated with the interval starting at
// low, or false if no such value exists.
func (t *Tree[I, V]) Get(low I) (KV[I, V], bool) {
n := t.root.search(low)
if n == nil {
return KV[I, V]{}, false
}
return newKV(n), true
}
// Each calls 'fn' on every element in the tree, and its corresponding
// interval, in order sorted by starting position.
func (t *Tree[I, V]) Each(fn func(low, high I, val V)) {
t.root.each(fn)
}
// Height returns the height of the tree.
func (t *Tree[I, V]) Height() int {
return t.root.getHeight()
}
// Size returns the number of elements in the tree.
func (t *Tree[I, V]) Size() int {
return t.root.size()
}
type node[I constraints.Ordered, V any] struct {
key intrvl[I]
value V
height int
left *node[I, V]
right *node[I, V]
// max is highest upper bound of all intervals stored in subtree which
// node as its root.
max I
}
// insert inserts interval key associated with value value to the tree.
//
// If interval starting at key.low already exists in a tree, behaviour of this
// method is defined by overwrite parameter. If it's true, the value is
// replaced. Otherwise whole subtree is left unchanged.
//
// This method returns new root node of a subtree rooted in n after insertion,
// an interval starting at key.low which already exists in the subtree and a
// flag if such an interval exists.
func (n *node[I, V]) insert(
key intrvl[I],
value V,
overwrite bool,
) (*node[I, V], KV[I, V], bool) {
if n == nil {
return &node[I, V]{
key: key,
value: value,
max: key.high,
height: 1,
left: nil,
right: nil,
}, KV[I, V]{}, false
}
var kv KV[I, V]
var evicted bool
if key.low < n.key.low {
n.left, kv, evicted = n.left.insert(key, value, overwrite)
} else if key.low > n.key.low {
n.right, kv, evicted = n.right.insert(key, value, overwrite)
} else {
if !overwrite {
return n, newKV(n), true
}
kv, evicted = newKV(n), true
n.key = key
n.value = value
}
return n.rebalanceTree(), kv, evicted
}
func (n *node[I, V]) updateMax() {
if n == nil {
return
}
n.max = n.key.high
if n.right != nil {
n.max = generic.Max(n.max, n.right.max)
}
if n.left != nil {
n.max = generic.Max(n.max, n.left.max)
}
}
// remove removes interval starting at pos from a subtree. This function returns
// the new root of subtree rooted in n after pos removal, the KV removed and an
// information if any deletion happened (i.e. if interval starting at pos
// exists).
func (n *node[I, V]) remove(low I) (*node[I, V], KV[I, V], bool) {
if n == nil {
return nil, KV[I, V]{}, false
}
var kv KV[I, V]
var removed bool
if low < n.key.low {
n.left, kv, removed = n.left.remove(low)
} else if low > n.key.low {
n.right, kv, removed = n.right.remove(low)
} else {
kv, removed = newKV(n), true
n = n.removeThis()
}
return n.rebalanceTree(), kv, removed
}
// removeThis deletes n from subtree rooted in n and returns new root of the
// subtree.
func (n *node[I, V]) removeThis() *node[I, V] {
// This can return nil if n has no children (n.right == nil).
if n.left == nil {
return n.right
}
if n.right == nil {
return n.left
}
rightMinNode := n.right.findSmallest()
n.key = rightMinNode.key
n.value = rightMinNode.value
n.right, _, _ = n.right.remove(rightMinNode.key.low)
return n
}
func (n *node[I, V]) search(low I) *node[I, V] {
if n == nil {
return nil
}
if low < n.key.low {
return n.left.search(low)
} else if low > n.key.low {
return n.right.search(low)
} else {
return n
}
}
func (n *node[I, V]) overlaps(key intrvl[I], result []KV[I, V]) []KV[I, V] {
if n == nil {
return result
}
if key.low >= n.max {
return result
}
result = n.left.overlaps(key, result)
if overlaps(n.key, key) {
result = append(result, newKV(n))
}
if key.high <= n.key.low {
return result
}
result = n.right.overlaps(key, result)
return result
}
func (n *node[I, V]) each(fn func(low, high I, val V)) {
if n == nil {
return
}
n.left.each(fn)
fn(n.key.low, n.key.high, n.value)
n.right.each(fn)
}
func (n *node[I, V]) getHeight() int {
if n == nil {
return 0
}
return n.height
}
func (n *node[I, V]) recalculateHeight() {
n.height = 1 + generic.Max(n.left.getHeight(), n.right.getHeight())
}
func (n *node[I, V]) rebalanceTree() *node[I, V] {
if n == nil {
return n
}
n.recalculateHeight()
n.updateMax()
balanceFactor := n.left.getHeight() - n.right.getHeight()
if balanceFactor <= -2 {
if n.right.left.getHeight() > n.right.right.getHeight() {
n.right = n.right.rotateRight()
}
return n.rotateLeft()
} else if balanceFactor >= 2 {
if n.left.right.getHeight() > n.left.left.getHeight() {
n.left = n.left.rotateLeft()
}
return n.rotateRight()
}
return n
}
func (n *node[I, V]) rotateLeft() *node[I, V] {
newRoot := n.right
n.right = newRoot.left
newRoot.left = n
n.recalculateHeight()
n.updateMax()
newRoot.recalculateHeight()
newRoot.updateMax()
return newRoot
}
func (n *node[I, V]) rotateRight() *node[I, V] {
newRoot := n.left
n.left = newRoot.right
newRoot.right = n
n.recalculateHeight()
n.updateMax()
newRoot.recalculateHeight()
newRoot.updateMax()
return newRoot
}
func (n *node[I, V]) findSmallest() *node[I, V] {
if n.left != nil {
return n.left.findSmallest()
} else {
return n
}
}
func (n *node[I, V]) size() int {
if n == nil {
return 0
}
s := 1
s += n.left.size()
s += n.right.size()
return s
}