-
Notifications
You must be signed in to change notification settings - Fork 292
/
TreapTree.cs
508 lines (420 loc) · 13.2 KB
/
TreapTree.cs
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A treap tree implementation.
/// </summary>
public class TreapTree<T> : IEnumerable<T> where T : IComparable
{
private readonly Random rndGenerator = new();
public TreapTree()
{
}
/// <summary>
/// Initialize the BST with given sorted keys.
/// Time complexity: O(n).
/// </summary>
/// <param name="sortedCollection">The initial sorted collection.</param>
public TreapTree(IEnumerable<T> sortedCollection) : this()
{
BstHelpers.ValidateSortedCollection(sortedCollection);
var nodes = sortedCollection.Select(x => new TreapTreeNode<T>(null, x, rndGenerator.Next())).ToArray();
Root = (TreapTreeNode<T>)BstHelpers.ToBst(nodes);
BstHelpers.AssignCount(Root);
Heapify(Root);
}
internal TreapTreeNode<T> Root { get; set; }
public int Count => Root == null ? 0 : Root.Count;
//Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return new BstEnumerator<T>(Root);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public bool HasItem(T value)
{
if (Root == null) return false;
return Find(Root, value) != null;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
internal int GetHeight()
{
return GetHeight(Root);
}
private int GetHeight(TreapTreeNode<T> node)
{
if (node == null) return -1;
return Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public void Insert(T value)
{
if (Root == null)
{
Root = new TreapTreeNode<T>(null, value, rndGenerator.Next());
return;
}
var newNode = Insert(Root, value);
Heapify(newNode);
}
//O(log(n)) always
private TreapTreeNode<T> Insert(TreapTreeNode<T> currentNode, T newNodeValue)
{
while (true)
{
var compareResult = currentNode.Value.CompareTo(newNodeValue);
//current node is less than new item
if (compareResult < 0)
{
//no right child
if (currentNode.Right == null)
{
//insert
currentNode.Right = new TreapTreeNode<T>(currentNode, newNodeValue, rndGenerator.Next());
return currentNode.Right;
}
currentNode = currentNode.Right;
}
//current node is greater than new node
else if (compareResult > 0)
{
if (currentNode.Left == null)
{
//insert
currentNode.Left = new TreapTreeNode<T>(currentNode, newNodeValue, rndGenerator.Next());
return currentNode.Left;
}
currentNode = currentNode.Left;
}
else
{
throw new Exception("Item exists");
}
}
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public int IndexOf(T item)
{
return Root.Position(item);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T ElementAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentNullException("index");
return Root.KthSmallest(index).Value;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public void Delete(T value)
{
if (Root == null) throw new Exception("Empty TreapTree");
Delete(Root, value);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T RemoveAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentException("index");
var nodeToDelete = Root.KthSmallest(index) as TreapTreeNode<T>;
Delete(nodeToDelete, nodeToDelete.Value);
return nodeToDelete.Value;
}
private void Delete(TreapTreeNode<T> node, T value)
{
while (true)
{
if (node != null)
{
var compareResult = node.Value.CompareTo(value);
//node is less than the search value so move right to find the deletion node
if (compareResult < 0)
{
node = node.Right ?? throw new Exception("Item do not exist");
continue;
}
//node is less than the search value so move left to find the deletion node
if (compareResult > 0)
{
node = node.Left ?? throw new Exception("Item do not exist");
continue;
}
}
//node is a leaf node
if (node != null && node.IsLeaf)
{
DeleteLeaf(node);
}
else
{
//case one - right tree is null (move sub tree up)
if (node?.Left != null && node.Right == null)
{
DeleteLeftNode(node);
}
//case two - left tree is null (move sub tree up)
else if (node?.Right != null && node.Left == null)
{
DeleteRightNode(node);
}
//case three - two child trees
//replace the node value with maximum element of left subtree (left max node)
//and then delete the left max node
else
{
if (node != null)
{
var maxLeftNode = FindMax(node.Left);
node.Value = maxLeftNode.Value;
//delete left max node
node = node.Left;
value = maxLeftNode.Value;
}
continue;
}
}
break;
}
node.UpdateCounts(true);
}
private void DeleteLeaf(TreapTreeNode<T> node)
{
//if node is root
if (node.Parent == null)
Root = null;
//assign nodes parent.left/right to null
else if (node.IsLeftChild)
node.Parent.Left = null;
else
node.Parent.Right = null;
}
private void DeleteRightNode(TreapTreeNode<T> node)
{
//root
if (node.Parent == null)
{
Root.Right.Parent = null;
Root = Root.Right;
return;
}
//node is left child of parent
if (node.IsLeftChild)
node.Parent.Left = node.Right;
//node is right child of parent
else
node.Parent.Right = node.Right;
node.Right.Parent = node.Parent;
}
private void DeleteLeftNode(TreapTreeNode<T> node)
{
//root
if (node.Parent == null)
{
Root.Left.Parent = null;
Root = Root.Left;
return;
}
//node is left child of parent
if (node.IsLeftChild)
node.Parent.Left = node.Left;
//node is right child of parent
else
node.Parent.Right = node.Left;
node.Left.Parent = node.Parent;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T FindMax()
{
return FindMax(Root).Value;
}
private TreapTreeNode<T> FindMax(TreapTreeNode<T> node)
{
while (true)
{
if (node.Right == null) return node;
node = node.Right;
}
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T FindMin()
{
return FindMin(Root).Value;
}
private TreapTreeNode<T> FindMin(TreapTreeNode<T> node)
{
while (true)
{
if (node.Left == null) return node;
node = node.Left;
}
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
private TreapTreeNode<T> Find(TreapTreeNode<T> parent, T value)
{
while (true)
{
if (parent == null) return null;
if (parent.Value.CompareTo(value) == 0) return parent;
var left = Find(parent.Left, value);
if (left != null) return left;
parent = parent.Right;
}
}
//reorder the tree node so that heap property is valid
private void Heapify(TreapTreeNode<T> node)
{
while (node.Parent != null)
{
node.UpdateCounts();
if (node.Priority < node.Parent.Priority)
node = node.IsLeftChild ? RightRotate(node.Parent) : LeftRotate(node.Parent);
else
break;
}
node.UpdateCounts(true);
}
/// <summary>
/// Rotates current root right and returns the new root node
/// </summary>
private TreapTreeNode<T> RightRotate(TreapTreeNode<T> currentRoot)
{
var prevRoot = currentRoot;
var leftRightChild = prevRoot.Left.Right;
var newRoot = currentRoot.Left;
//make left child as root
prevRoot.Left.Parent = prevRoot.Parent;
if (prevRoot.Parent != null)
{
if (prevRoot.Parent.Left == prevRoot)
prevRoot.Parent.Left = prevRoot.Left;
else
prevRoot.Parent.Right = prevRoot.Left;
}
//move prev root as right child of current root
newRoot.Right = prevRoot;
prevRoot.Parent = newRoot;
//move right child of left child of prev root to left child of right child of new root
newRoot.Right.Left = leftRightChild;
if (newRoot.Right.Left != null) newRoot.Right.Left.Parent = newRoot.Right;
newRoot.Left.UpdateCounts();
newRoot.Right.UpdateCounts();
newRoot.UpdateCounts();
if (prevRoot == Root) Root = newRoot;
return newRoot;
}
/// <summary>
/// Rotates the current root left and returns new root
/// </summary>
private TreapTreeNode<T> LeftRotate(TreapTreeNode<T> currentRoot)
{
var prevRoot = currentRoot;
var rightLeftChild = prevRoot.Right.Left;
var newRoot = currentRoot.Right;
//make right child as root
prevRoot.Right.Parent = prevRoot.Parent;
if (prevRoot.Parent != null)
{
if (prevRoot.Parent.Left == prevRoot)
prevRoot.Parent.Left = prevRoot.Right;
else
prevRoot.Parent.Right = prevRoot.Right;
}
//move prev root as left child of current root
newRoot.Left = prevRoot;
prevRoot.Parent = newRoot;
//move left child of right child of prev root to right child of left child of new root
newRoot.Left.Right = rightLeftChild;
if (newRoot.Left.Right != null) newRoot.Left.Right.Parent = newRoot.Left;
newRoot.Left.UpdateCounts();
newRoot.Right.UpdateCounts();
newRoot.UpdateCounts();
if (prevRoot == Root) Root = newRoot;
return newRoot;
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
private BstNodeBase<T> Find(T value)
{
return Root.Find(value).Item1;
}
/// <summary>
/// Get the next lower value to given value in this BST.
/// Time complexity: O(n).
/// </summary>
public T NextLower(T value)
{
var node = Find(value);
if (node == null) return default;
var next = node.NextLower();
return next != null ? next.Value : default;
}
/// <summary>
/// Get the next higher value to given value in this BST.
/// Time complexity: O(n).
/// </summary>
public T NextHigher(T value)
{
var node = Find(value);
if (node == null) return default;
var next = node.NextHigher();
return next != null ? next.Value : default;
}
/// <summary>
/// Descending enumerable.
/// </summary>
public IEnumerable<T> AsEnumerableDesc()
{
return GetEnumeratorDesc().AsEnumerable();
}
public IEnumerator<T> GetEnumeratorDesc()
{
return new BstEnumerator<T>(Root, false);
}
}
internal class TreapTreeNode<T> : BstNodeBase<T> where T : IComparable
{
internal TreapTreeNode(TreapTreeNode<T> parent, T value, int priority)
{
Parent = parent;
Value = value;
Priority = priority;
}
internal new TreapTreeNode<T> Parent
{
get => (TreapTreeNode<T>)base.Parent;
set => base.Parent = value;
}
internal new TreapTreeNode<T> Left
{
get => (TreapTreeNode<T>)base.Left;
set => base.Left = value;
}
internal new TreapTreeNode<T> Right
{
get => (TreapTreeNode<T>)base.Right;
set => base.Right = value;
}
internal int Priority { get; set; }
}