-
Notifications
You must be signed in to change notification settings - Fork 271
/
binary_trees.py
1889 lines (1627 loc) · 63.6 KB
/
binary_trees.py
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
from collections import deque as Queue
from pydatastructs.utils import TreeNode, CartesianTreeNode, RedBlackTreeNode
from pydatastructs.miscellaneous_data_structures import Stack
from pydatastructs.linear_data_structures import OneDimensionalArray
from pydatastructs.linear_data_structures.arrays import ArrayForTrees
from pydatastructs.utils.misc_util import (
Backend, raise_if_backend_is_not_python)
from pydatastructs.trees._backend.cpp import _trees
__all__ = [
'AVLTree',
'BinaryTree',
'BinarySearchTree',
'BinaryTreeTraversal',
'BinaryIndexedTree',
'CartesianTree',
'Treap',
'SplayTree',
'RedBlackTree'
]
class BinaryTree(object):
"""
Abstract binary tree.
Parameters
==========
key
Required if tree is to be instantiated with
root otherwise not needed.
root_data
Optional, the root node of the binary tree.
If not of type TreeNode, it will consider
root as data and a new root node will
be created.
comp: lambda/function
Optional, A lambda function which will be used
for comparison of keys. Should return a
bool value. By default it implements less
than operator.
is_order_statistic: bool
Set it to True, if you want to use the
order statistic features of the tree.
backend: pydatastructs.Backend
The backend to be used. Available backends: Python and C++
Optional, by default, the Python backend is used. For faster execution, use the C++ backend.
References
==========
.. [1] https://en.wikipedia.org/wiki/Binary_tree
"""
__slots__ = ['root_idx', 'comparator', 'tree', 'size',
'is_order_statistic']
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.BinaryTree(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
obj = object.__new__(cls)
if key is None and root_data is not None:
raise ValueError('Key required.')
key = None if root_data is None else key
root = TreeNode(key, root_data)
root.is_root = True
obj.root_idx = 0
obj.tree, obj.size = ArrayForTrees(TreeNode, [root]), 1
obj.comparator = lambda key1, key2: key1 < key2 \
if comp is None else comp
obj.is_order_statistic = is_order_statistic
return obj
@classmethod
def methods(cls):
return ['__new__', '__str__']
def insert(self, key, data=None):
"""
Inserts data by the passed key using iterative
algorithm.
Parameters
==========
key
The key for comparison.
data
The data to be inserted.
Returns
=======
None
"""
raise NotImplementedError("This is an abstract method.")
def delete(self, key, **kwargs):
"""
Deletes the data with the passed key
using iterative algorithm.
Parameters
==========
key
The key of the node which is
to be deleted.
balancing_info: bool
Optional, by default, False
The information needed for updating
the tree is returned if this parameter
is set to True. It is not meant for
user facing APIs.
Returns
=======
True
If the node is deleted successfully.
None
If the node to be deleted doesn't exists.
Note
====
The node is deleted means that the connection to that
node are removed but the it is still in three. This
is being done to keep the complexity of deletion, O(logn).
"""
raise NotImplementedError("This is an abstract method.")
def search(self, key, **kwargs):
"""
Searches for the data in the binary search tree
using iterative algorithm.
Parameters
==========
key
The key for searching.
parent: bool
If true then returns index of the
parent of the node with the passed
key.
By default, False
Returns
=======
int
If the node with the passed key is
in the tree.
tuple
The index of the searched node and
the index of the parent of that node.
None
In all other cases.
"""
raise NotImplementedError("This is an abstract method.")
def __str__(self):
to_be_printed = ['' for i in range(self.tree._last_pos_filled + 1)]
for i in range(self.tree._last_pos_filled + 1):
if self.tree[i] is not None:
node = self.tree[i]
to_be_printed[i] = (node.left, node.key, node.data, node.right)
return str(to_be_printed)
class BinarySearchTree(BinaryTree):
"""
Represents binary search trees.
Examples
========
>>> from pydatastructs.trees import BinarySearchTree as BST
>>> b = BST()
>>> b.insert(1, 1)
>>> b.insert(2, 2)
>>> child = b.tree[b.root_idx].right
>>> b.tree[child].data
2
>>> b.search(1)
0
>>> b.search(-1) is None
True
>>> b.delete(1) is True
True
>>> b.search(1) is None
True
>>> b.delete(2) is True
True
>>> b.search(2) is None
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Binary_search_tree
See Also
========
pydatastructs.trees.binary_tree.BinaryTree
"""
@classmethod
def methods(cls):
return ['insert', 'search', 'delete', 'select',
'rank', 'lowest_common_ancestor']
left_size = lambda self, node: self.tree[node.left].size \
if node.left is not None else 0
right_size = lambda self, node: self.tree[node.right].size \
if node.right is not None else 0
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.BinarySearchTree(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
return super().__new__(cls, key, root_data, comp, is_order_statistic, **kwargs)
def _update_size(self, start_idx):
if self.is_order_statistic:
walk = start_idx
while walk is not None:
self.tree[walk].size = (
self.left_size(self.tree[walk]) +
self.right_size(self.tree[walk]) + 1)
walk = self.tree[walk].parent
def insert(self, key, data=None):
res = self.search(key)
if res is not None:
self.tree[res].data = data
return None
walk = self.root_idx
if self.tree[walk].key is None:
self.tree[walk].key = key
self.tree[walk].data = data
return None
new_node, prev_node, flag = TreeNode(key, data), self.root_idx, True
while flag:
if not self.comparator(key, self.tree[walk].key):
if self.tree[walk].right is None:
new_node.parent = prev_node
self.tree.append(new_node)
self.tree[walk].right = self.size
self.size += 1
flag = False
prev_node = walk = self.tree[walk].right
else:
if self.tree[walk].left is None:
new_node.parent = prev_node
self.tree.append(new_node)
self.tree[walk].left = self.size
self.size += 1
flag = False
prev_node = walk = self.tree[walk].left
self._update_size(walk)
def search(self, key, **kwargs):
ret_parent = kwargs.get('parent', False)
parent = None
walk = self.root_idx
if self.tree[walk].key is None:
return None
while walk is not None:
if self.tree[walk].key == key:
break
parent = walk
if self.comparator(key, self.tree[walk].key):
walk = self.tree[walk].left
else:
walk = self.tree[walk].right
return (walk, parent) if ret_parent else walk
def _bound_helper(self, node_idx, bound_key, is_upper=False):
if node_idx is None:
return None
if self.tree[node_idx].key is None:
return None
if self.tree[node_idx].key == bound_key:
if not is_upper:
return self.tree[node_idx].key
else:
return self._bound_helper(self.tree[node_idx].right,
bound_key, is_upper)
if self.comparator(self.tree[node_idx].key, bound_key):
return self._bound_helper(self.tree[node_idx].right,
bound_key, is_upper)
else:
res_bound = self._bound_helper(self.tree[node_idx].left,
bound_key, is_upper)
return res_bound if res_bound is not None else self.tree[node_idx].key
def lower_bound(self, key, **kwargs):
"""
Finds the lower bound of the given key in the tree
Parameters
==========
key
The key for comparison
Examples
========
>>> from pydatastructs.trees import BinarySearchTree as BST
>>> b = BST()
>>> b.insert(10, 10)
>>> b.insert(18, 18)
>>> b.insert(7, 7)
>>> b.lower_bound(9)
10
>>> b.lower_bound(7)
7
>>> b.lower_bound(20) is None
True
Returns
=======
value
The lower bound of the given key.
Returns None if the value doesn't exist
"""
return self._bound_helper(self.root_idx, key)
def upper_bound(self, key, **kwargs):
"""
Finds the upper bound of the given key in the tree
Parameters
==========
key
The key for comparison
Examples
========
>>> from pydatastructs.trees import BinarySearchTree as BST
>>> b = BST()
>>> b.insert(10, 10)
>>> b.insert(18, 18)
>>> b.insert(7, 7)
>>> b.upper_bound(9)
10
>>> b.upper_bound(7)
10
>>> b.upper_bound(20) is None
True
Returns
=======
value
The upper bound of the given key.
Returns None if the value doesn't exist
"""
return self._bound_helper(self.root_idx, key, True)
def delete(self, key, **kwargs):
(walk, parent) = self.search(key, parent=True)
a = None
if walk is None:
return None
if self.tree[walk].left is None and \
self.tree[walk].right is None:
if parent is None:
self.tree[self.root_idx].data = None
self.tree[self.root_idx].key = None
else:
if self.tree[parent].left == walk:
self.tree[parent].left = None
else:
self.tree[parent].right = None
a = parent
par_key, root_key = (self.tree[parent].key,
self.tree[self.root_idx].key)
new_indices = self.tree.delete(walk)
if new_indices is not None:
a = new_indices[par_key]
self.root_idx = new_indices[root_key]
self._update_size(a)
elif self.tree[walk].left is not None and \
self.tree[walk].right is not None:
twalk = self.tree[walk].right
par = walk
flag = False
while self.tree[twalk].left is not None:
flag = True
par = twalk
twalk = self.tree[twalk].left
self.tree[walk].data = self.tree[twalk].data
self.tree[walk].key = self.tree[twalk].key
if flag:
self.tree[par].left = self.tree[twalk].right
else:
self.tree[par].right = self.tree[twalk].right
if self.tree[twalk].right is not None:
self.tree[self.tree[twalk].right].parent = par
if twalk is not None:
a = par
par_key, root_key = (self.tree[par].key,
self.tree[self.root_idx].key)
new_indices = self.tree.delete(twalk)
if new_indices is not None:
a = new_indices[par_key]
self.root_idx = new_indices[root_key]
self._update_size(a)
else:
if self.tree[walk].left is not None:
child = self.tree[walk].left
else:
child = self.tree[walk].right
if parent is None:
self.tree[self.root_idx].left = self.tree[child].left
self.tree[self.root_idx].right = self.tree[child].right
self.tree[self.root_idx].data = self.tree[child].data
self.tree[self.root_idx].key = self.tree[child].key
self.tree[self.root_idx].parent = None
root_key = self.tree[self.root_idx].key
new_indices = self.tree.delete(child)
if new_indices is not None:
self.root_idx = new_indices[root_key]
else:
if self.tree[parent].left == walk:
self.tree[parent].left = child
else:
self.tree[parent].right = child
self.tree[child].parent = parent
a = parent
par_key, root_key = (self.tree[parent].key,
self.tree[self.root_idx].key)
new_indices = self.tree.delete(walk)
if new_indices is not None:
parent = new_indices[par_key]
self.tree[child].parent = new_indices[par_key]
a = new_indices[par_key]
self.root_idx = new_indices[root_key]
self._update_size(a)
if kwargs.get("balancing_info", False) is not False:
return a
return True
def select(self, i):
"""
Finds the i-th smallest node in the tree.
Parameters
==========
i: int
A positive integer
Returns
=======
n: TreeNode
The node with the i-th smallest key
References
==========
.. [1] https://en.wikipedia.org/wiki/Order_statistic_tree
"""
i -= 1 # The algorithm is based on zero indexing
if i < 0:
raise ValueError("Expected a positive integer, got %d"%(i + 1))
if i >= self.tree._num:
raise ValueError("%d is greater than the size of the "
"tree which is, %d"%(i + 1, self.tree._num))
walk = self.root_idx
while walk is not None:
l = self.left_size(self.tree[walk])
if i == l:
return self.tree[walk]
left_walk = self.tree[walk].left
right_walk = self.tree[walk].right
if left_walk is None and right_walk is None:
raise IndexError("The traversal is terminated "
"due to no child nodes ahead.")
if i < l:
if left_walk is not None and \
self.comparator(self.tree[left_walk].key,
self.tree[walk].key):
walk = left_walk
else:
walk = right_walk
else:
if right_walk is not None and \
not self.comparator(self.tree[right_walk].key,
self.tree[walk].key):
walk = right_walk
else:
walk = left_walk
i -= (l + 1)
def rank(self, x):
"""
Finds the rank of the given node, i.e.
its index in the sorted list of nodes
of the tree.
Parameters
==========
x: key
The key of the node whose rank is to be found out.
"""
walk = self.search(x)
if walk is None:
return None
r = self.left_size(self.tree[walk]) + 1
while self.tree[walk].key != self.tree[self.root_idx].key:
p = self.tree[walk].parent
if walk == self.tree[p].right:
r += self.left_size(self.tree[p]) + 1
walk = p
return r
def _simple_path(self, key, root):
"""
Utility funtion to find the simple path between root and node.
Parameters
==========
key: Node.key
Key of the node to be searched
Returns
=======
path: list
"""
stack = Stack()
stack.push(root)
path = []
node_idx = -1
while not stack.is_empty:
node = stack.pop()
if self.tree[node].key == key:
node_idx = node
break
if self.tree[node].left:
stack.push(self.tree[node].left)
if self.tree[node].right:
stack.push(self.tree[node].right)
if node_idx == -1:
return path
while node_idx != 0:
path.append(node_idx)
node_idx = self.tree[node_idx].parent
path.append(0)
path.reverse()
return path
def _lca_1(self, j, k):
root = self.root_idx
path1 = self._simple_path(j, root)
path2 = self._simple_path(k, root)
if not path1 or not path2:
raise ValueError("One of two path doesn't exists. See %s, %s"
%(path1, path2))
n, m = len(path1), len(path2)
i = j = 0
while i < n and j < m:
if path1[i] != path2[j]:
return self.tree[path1[i - 1]].key
i += 1
j += 1
if path1 < path2:
return self.tree[path1[-1]].key
return self.tree[path2[-1]].key
def _lca_2(self, j, k):
curr_root = self.root_idx
u, v = self.search(j), self.search(k)
if (u is None) or (v is None):
raise ValueError("One of the nodes with key %s "
"or %s doesn't exits"%(j, k))
u_left = self.comparator(self.tree[u].key, \
self.tree[curr_root].key)
v_left = self.comparator(self.tree[v].key, \
self.tree[curr_root].key)
while not (u_left ^ v_left):
if u_left and v_left:
curr_root = self.tree[curr_root].left
else:
curr_root = self.tree[curr_root].right
if curr_root == u or curr_root == v:
if curr_root is None:
return None
return self.tree[curr_root].key
u_left = self.comparator(self.tree[u].key, \
self.tree[curr_root].key)
v_left = self.comparator(self.tree[v].key, \
self.tree[curr_root].key)
if curr_root is None:
return curr_root
return self.tree[curr_root].key
def lowest_common_ancestor(self, j, k, algorithm=1):
"""
Computes the lowest common ancestor of two nodes.
Parameters
==========
j: Node.key
Key of first node
k: Node.key
Key of second node
algorithm: int
The algorithm to be used for computing the
lowest common ancestor.
Optional, by default uses algorithm 1.
1 -> Determines the lowest common ancestor by finding
the first intersection of the paths from v and w
to the root.
2 -> Modifed version of the algorithm given in the
following publication,
D. Harel. A linear time algorithm for the
lowest common ancestors problem. In 21s
Annual Symposium On Foundations of
Computer Science, pages 308-319, 1980.
Returns
=======
Node.key
The key of the lowest common ancestor in the tree.
if both the nodes are present in the tree.
References
==========
.. [1] https://en.wikipedia.org/wiki/Lowest_common_ancestor
.. [2] https://pdfs.semanticscholar.org/e75b/386cc554214aa0ebd6bd6dbdd0e490da3739.pdf
"""
return getattr(self, "_lca_"+str(algorithm))(j, k)
class SelfBalancingBinaryTree(BinarySearchTree):
"""
Represents Base class for all rotation based balancing trees like AVL tree, Red Black tree, Splay Tree.
"""
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.SelfBalancingBinaryTree(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
return super().__new__(cls, key, root_data, comp, is_order_statistic, **kwargs)
def _right_rotate(self, j, k):
y = self.tree[k].right
if y is not None:
self.tree[y].parent = j
self.tree[j].left = y
self.tree[k].parent = self.tree[j].parent
if self.tree[k].parent is not None:
if self.tree[self.tree[k].parent].left == j:
self.tree[self.tree[k].parent].left = k
else:
self.tree[self.tree[k].parent].right = k
self.tree[j].parent = k
self.tree[k].right = j
kp = self.tree[k].parent
if kp is None:
self.root_idx = k
def _left_right_rotate(self, j, k):
i = self.tree[k].right
v, w = self.tree[i].left, self.tree[i].right
self.tree[k].right, self.tree[j].left = v, w
if v is not None:
self.tree[v].parent = k
if w is not None:
self.tree[w].parent = j
self.tree[i].left, self.tree[i].right, self.tree[i].parent = \
k, j, self.tree[j].parent
self.tree[k].parent, self.tree[j].parent = i, i
ip = self.tree[i].parent
if ip is not None:
if self.tree[ip].left == j:
self.tree[ip].left = i
else:
self.tree[ip].right = i
else:
self.root_idx = i
def _right_left_rotate(self, j, k):
i = self.tree[k].left
v, w = self.tree[i].left, self.tree[i].right
self.tree[k].left, self.tree[j].right = w, v
if v is not None:
self.tree[v].parent = j
if w is not None:
self.tree[w].parent = k
self.tree[i].right, self.tree[i].left, self.tree[i].parent = \
k, j, self.tree[j].parent
self.tree[k].parent, self.tree[j].parent = i, i
ip = self.tree[i].parent
if ip is not None:
if self.tree[ip].left == j:
self.tree[ip].left = i
else:
self.tree[ip].right = i
else:
self.root_idx = i
def _left_rotate(self, j, k):
y = self.tree[k].left
if y is not None:
self.tree[y].parent = j
self.tree[j].right = y
self.tree[k].parent = self.tree[j].parent
if self.tree[k].parent is not None:
if self.tree[self.tree[k].parent].left == j:
self.tree[self.tree[k].parent].left = k
else:
self.tree[self.tree[k].parent].right = k
self.tree[j].parent = k
self.tree[k].left = j
kp = self.tree[k].parent
if kp is None:
self.root_idx = k
class CartesianTree(SelfBalancingBinaryTree):
"""
Represents cartesian trees.
Examples
========
>>> from pydatastructs.trees import CartesianTree as CT
>>> c = CT()
>>> c.insert(1, 4, 1)
>>> c.insert(2, 3, 2)
>>> child = c.tree[c.root_idx].left
>>> c.tree[child].data
1
>>> c.search(1)
0
>>> c.search(-1) is None
True
>>> c.delete(1) is True
True
>>> c.search(1) is None
True
>>> c.delete(2) is True
True
>>> c.search(2) is None
True
References
==========
.. [1] https://www.cs.princeton.edu/courses/archive/spr09/cos423/Lectures/geo-st.pdf
See Also
========
pydatastructs.trees.binary_trees.SelfBalancingBinaryTree
"""
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.CartesianTree(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
return super().__new__(cls, key, root_data, comp, is_order_statistic, **kwargs)
@classmethod
def methods(cls):
return ['__new__', '__str__', 'insert', 'delete']
def _bubble_up(self, node_idx):
node = self.tree[node_idx]
parent_idx = self.tree[node_idx].parent
parent = self.tree[parent_idx]
while (node.parent is not None) and (parent.priority > node.priority):
if parent.right == node_idx:
self._left_rotate(parent_idx, node_idx)
else:
self._right_rotate(parent_idx, node_idx)
node = self.tree[node_idx]
parent_idx = self.tree[node_idx].parent
if parent_idx is not None:
parent = self.tree[parent_idx]
if node.parent is None:
self.tree[node_idx].is_root = True
def _trickle_down(self, node_idx):
node = self.tree[node_idx]
while node.left is not None or node.right is not None:
if node.left is None:
self._left_rotate(node_idx, self.tree[node_idx].right)
elif node.right is None:
self._right_rotate(node_idx, self.tree[node_idx].left)
elif self.tree[node.left].priority < self.tree[node.right].priority:
self._right_rotate(node_idx, self.tree[node_idx].left)
else:
self._left_rotate(node_idx, self.tree[node_idx].right)
node = self.tree[node_idx]
def insert(self, key, priority, data=None):
super(CartesianTree, self).insert(key, data)
node_idx = super(CartesianTree, self).search(key)
node = self.tree[node_idx]
new_node = CartesianTreeNode(key, priority, data)
new_node.parent = node.parent
new_node.left = node.left
new_node.right = node.right
self.tree[node_idx] = new_node
if node.is_root:
self.tree[node_idx].is_root = True
else:
self._bubble_up(node_idx)
def delete(self, key, **kwargs):
balancing_info = kwargs.get('balancing_info', False)
node_idx = super(CartesianTree, self).search(key)
if node_idx is not None:
self._trickle_down(node_idx)
return super(CartesianTree, self).delete(key, balancing_info = balancing_info)
def __str__(self):
to_be_printed = ['' for i in range(self.tree._last_pos_filled + 1)]
for i in range(self.tree._last_pos_filled + 1):
if self.tree[i] is not None:
node = self.tree[i]
to_be_printed[i] = (node.left, node.key, node.priority, node.data, node.right)
return str(to_be_printed)
class Treap(CartesianTree):
"""
Represents treaps.
Examples
========
>>> from pydatastructs.trees import Treap as T
>>> t = T()
>>> t.insert(1, 1)
>>> t.insert(2, 2)
>>> t.search(1)
0
>>> t.search(-1) is None
True
>>> t.delete(1) is True
True
>>> t.search(1) is None
True
>>> t.delete(2) is True
True
>>> t.search(2) is None
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Treap
"""
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.Treap(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
return super().__new__(cls, key, root_data, comp, is_order_statistic, **kwargs)
@classmethod
def methods(cls):
return ['__new__', 'insert']
def insert(self, key, data=None):
priority = random.random()
super(Treap, self).insert(key, priority, data)
class AVLTree(SelfBalancingBinaryTree):
"""
Represents AVL trees.
References
==========
.. [1] https://courses.cs.washington.edu/courses/cse373/06sp/handouts/lecture12.pdf
.. [2] https://en.wikipedia.org/wiki/AVL_tree
.. [3] http://faculty.cs.niu.edu/~freedman/340/340notes/340avl2.htm
See Also
========
pydatastructs.trees.binary_trees.BinaryTree
"""
def __new__(cls, key=None, root_data=None, comp=None,
is_order_statistic=False, **kwargs):
backend = kwargs.get('backend', Backend.PYTHON)
if backend == Backend.CPP:
if comp is None:
comp = lambda key1, key2: key1 < key2
return _trees.AVLTree(key, root_data, comp, is_order_statistic, **kwargs) # If any argument is not given, then it is passed as None, except for comp
return super().__new__(cls, key, root_data, comp, is_order_statistic, **kwargs)
@classmethod
def methods(cls):
return ['__new__', 'set_tree', 'insert', 'delete']
left_height = lambda self, node: self.tree[node.left].height \
if node.left is not None else -1
right_height = lambda self, node: self.tree[node.right].height \
if node.right is not None else -1
balance_factor = lambda self, node: self.right_height(node) - \
self.left_height(node)
def set_tree(self, arr):
self.tree = arr
def _right_rotate(self, j, k):
super(AVLTree, self)._right_rotate(j, k)
self.tree[j].height = max(self.left_height(self.tree[j]),
self.right_height(self.tree[j])) + 1
if self.is_order_statistic:
self.tree[j].size = (self.left_size(self.tree[j]) +
self.right_size(self.tree[j]) + 1)
def _left_right_rotate(self, j, k):
super(AVLTree, self)._left_right_rotate(j, k)
self.tree[j].height = max(self.left_height(self.tree[j]),
self.right_height(self.tree[j])) + 1
self.tree[k].height = max(self.left_height(self.tree[k]),
self.right_height(self.tree[k])) + 1
if self.is_order_statistic:
self.tree[j].size = (self.left_size(self.tree[j]) +
self.right_size(self.tree[j]) + 1)
self.tree[k].size = (self.left_size(self.tree[k]) +
self.right_size(self.tree[k]) + 1)
def _right_left_rotate(self, j, k):
super(AVLTree, self)._right_left_rotate(j, k)
self.tree[j].height = max(self.left_height(self.tree[j]),
self.right_height(self.tree[j])) + 1
self.tree[k].height = max(self.left_height(self.tree[k]),
self.right_height(self.tree[k])) + 1
if self.is_order_statistic:
self.tree[j].size = (self.left_size(self.tree[j]) +
self.right_size(self.tree[j]) + 1)
self.tree[k].size = (self.left_size(self.tree[k]) +
self.right_size(self.tree[k]) + 1)
def _left_rotate(self, j, k):
super(AVLTree, self)._left_rotate(j, k)
self.tree[j].height = max(self.left_height(self.tree[j]),
self.right_height(self.tree[j])) + 1
self.tree[k].height = max(self.left_height(self.tree[k]),