-
Notifications
You must be signed in to change notification settings - Fork 1
/
avl_template_new.py
1317 lines (1024 loc) · 30.6 KB
/
avl_template_new.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
#username - complete info
#id1 - complete info
#name1 - complete info
#id2 - complete info
#name2 - complete info
import random
class AVLNode(object):
""" AVL Node
--------
A class represnting a node in an AVL tree
@inv: for each node, abs(left.height - right.height) <= 1 # AVL
fields
------
value: data held in node @type: str
pointers:
left: left child of the node @type: AVLNode \n
right: right child of the node @type: AVLNode \n
parent: parent of the node @type:AVLNode \n
helpers:
height: length of the longest path from the node to a leaf @type: int \n
size: the number of nodes in the subtree @type: int
"""
def __init__(self, value, left=None, right=None, height=None, size=None,
parent=None, is_real=True):
"""Constructor, creates a node.
if node should be a real node, pads with virtuals
@type value: str or None
@param value: data of your node
@type left: AVLNode
@param left: left child the node
@type right: AVLNode
@param right: right child of the node
@type height: int
@param height: length of the longest path to a leaf. Updates from children if None
@type size: int
@param size: the number of nodes in the subtree. Updates from children if None
@type parent: AVLNode
@param parent: parent of the node
@type is_real: bool
@param is_real: is this node real or not
@time complexity: O(1)
"""
# Convention: attributes starting with p_ are private
self.p_value = value
# pointers
self.p_left = left
self.p_right = right
self.p_parent = parent
# padding with virtual nodes
if (is_real):
self.padWithVirtuals()
# help fields
self.p_height = height
if height == None:
self.updateHeight()
self.p_size = size
if size == None:
self.updateSize()
@staticmethod
def virtualNode(parent=None):
"""creates a new virtual node assigned with given parent
@type parent: AVLNode
@param parent: node to be the parent
@time complexity: O(1)
"""
return AVLNode( value=None,
left=None,
right=None,
height=-1,
size=0,
parent=parent,
is_real=False)
def __repr__(self):
""" Overrides the str representation of a node.
@rtype: str
@return: "node" and then the value of the node
@time complexity: O(1)
"""
if self.isRealNode():
return f"node: {self.getValue()}"
return "a virtual node"
def __getattr__(self, name):
"""Overrides get attributes.
Runs iff __getarttribute__ couldn't find name.
Should not be called explicitly, only by using
node_instance.name
@type name: str
@param name: the attribute to be found
@time complexity: O(1)
"""
if name == "value":
return self.getValue()
elif name == "right":
return self.getRight()
elif name == "left":
return self.getLeft()
elif name == "parent":
return self.getParent()
elif name == "height":
return self.getHeight()
elif name == "size":
return self.getSize()
elif name == "balance_factor":
return self.getBalanceFactor()
def __setattr__(self, name, value):
"""Overrides some set attributes
if none of the options, falls back to default behavior
Should not be called explicitly, only by using
node_instance.name = value
@type name: str
@param name: the attribute to be set
@time complexity: O(1)
"""
if name == "value":
self.setValue(value)
elif name == "right":
self.setRight(value)
elif name == "left":
self.setLeft(value)
elif name == "parent":
self.setParent(value)
elif name == "height":
self.setHeight(value)
elif name == "size":
self.setSize(value)
else: # default behavior
object.__setattr__(self, name, value)
def getLeft(self):
"""returns the left child
@rtype: AVLNode
@returns: the left child of self, virtualNode if there is no left child
@time complexity: O(1)
"""
left = self.p_left
if left == None and self.isRealNode():
return AVLNode.virtualNode(self)
return left
def getRight(self):
"""returns the right child
@rtype: AVLNode
@returns: the right child of self, None if there is no right child
@time complexity: O(1)
"""
right = self.p_right
if right == None and self.isRealNode():
return AVLNode.virtualNode(self)
return right
def hasLeft(self):
"""checks if the left child is a real node
@rtype: bool
@return: left != None and left is a real node
@time complexity: O(1)
"""
left = self.getLeft()
return left != None and left.isRealNode()
def hasRight(self):
"""checks if the right child is a real node
@rtype: bool
@return: right != None and right is a real node
@time complexity: O(1)
"""
right = self.getRight()
return right != None and right.isRealNode()
def getParent(self):
"""returns the parent
@rtype: AVLNode
@returns: the parent of self, None if there is no parent
@time complexity: O(1)
"""
return self.p_parent
def getValue(self):
"""return the value
@rtype: str
@returns: the value of self, None if the node is virtual
@time complexity: O(1)
"""
return self.p_value
def getSize(self):
"""returns the size field
@rtype: int
@returns: the number of nodes in the subtree below self (inclusive)
Doesn't check for correctness
@time complexity: O(1)
"""
return self.p_size
def getHeight(self):
"""returns the height field
@pre: height is correct
@rtype: int
@returns: the height of self, -1 if the node is virtual.
@time complexity: O(1)
"""
return self.p_height
def getBalanceFactor(self):
"""returns the balance_factor
@pre: height correct for all fields
@rtype: int
@returns: the balace factor of self, 0 if the node is virtual
@time complexity: O(1)
"""
if not self.isRealNode():
return 0
right_height = self.getRight().getHeight()
left_height = self.getLeft().getHeight()
return left_height - right_height
def getRank(self):
"""gets the rank of a node.
inOrder(tree)[self.getRank()-1] == self
@rtype: int
@return: the rank of self
@time complexity: O(log n)
"""
rank = self.getLeft().getSize() + 1
node = self
while (node != None):
parent = node.getParent()
if ((parent != None) and (node is parent.getRight())):
# using 'is' to make sure it has the same memory address
rank += parent.getLeft().getSize() + 1
node = parent
return rank
def setLeft(self, node):
"""sets left child
@post: doesn't update help fields
@post: old left deleted
@post: does not rebalance
@type node: AVLNode
@param node: a node
@time complexity: O(1)
"""
self.p_left = node
def setRight(self, node):
"""sets right child
@post: doesn't update help fields
@post: old right deleted
@post: does not rebalance
@type node: AVLNode
@param node: a node
@time complexity: O(1)
"""
self.p_right = node
def setParent(self, parent):
"""sets parent
@post: old parent deleted
@post: doesn't affect parent
@type parent: AVLNode
@param parent: a node to be the parent of self
@time complexity: O(1)
"""
self.p_parent = parent
def setValue(self, value):
"""sets value.
@post: If self was virtual, updates help fields and pads with virtual nodes
@type value: str
@param value: data
@time complexity: O(1)
"""
if (not self.isRealNode()):
self.p_size = 1
self.p_height = 0
self.padWithVirtuals()
self.p_value = value
def padWithVirtuals(self):
"""adds virtual nodes where self has no children
@time complexity: O(1)
"""
left = self.p_left # unsafe attribute access
if (left == None):
self.p_left = AVLNode.virtualNode(parent=self)
right = self.p_right # unsafe attribute access
if (right == None):
self.p_right = AVLNode.virtualNode(parent=self)
def setSize(self, s):
"""sets the size of the node
@pre: inserted size is correct
@type s: int
@param s: the size
@time complexity: O(1)
"""
self.p_size = s
def setHeight(self, h):
"""sets the height of the node
@pre: inserted height is correct
@type h: int
@param h: the height
@time complexity: O(1)
"""
self.p_height = h
def updateSize(self):
"""sets the size based on the sizes of the left and the right children
@pre: children sizes are updated
@time complexity: O(1)
"""
left = self.getLeft()
right = self.getRight()
self.setSize(left.getSize() + right.getSize() + 1)
def updateHeight(self):
"""sets the height based on the heights of the left and the right children
@pre: children heights are updated
@time complexity: O(1)
"""
left_height = self.getLeft().getHeight()
right_height = self.getRight().getHeight()
self.setHeight(max(left_height, right_height) + 1)
def updateHelpers(self):
"""Updates both height and size
@pre: children size and height are correct
@time complexity: O(1)
"""
self.updateHeight()
self.updateSize()
def updateHereAndUp(self):
"""Updates the help field of self and his parents, up to the root
@time complexity: O(log n)
"""
node = self
while (node != None):
node.updateHelpers()
node = node.getParent()
def isRealNode(self):
"""returns whether self is not a virtual node
@rtype: bool
@returns: False if self is a virtual node, True otherwise.
@time complexity: O(1)
"""
return self.p_height != -1 and self.p_size != 0
def rebalance(self, is_insert = False):
"""rebalance the tree after insertion or deletion of self
@pre: the tree was AVL before modification
@pre: help fields were not updated
@post help fields are updated
@type is_insert: bool
@param is_insert: if rebalance is after insertion
@rtype: int
@return: number of rotations
@time complexity: O(log n)
"""
rotations_count = 0
parent = self.getParent()
while parent != None:
old_height = parent.getHeight()
parent.updateHelpers()
balance_factor = parent.getBalanceFactor()
new_height = parent.getHeight()
if ((-2 < balance_factor < 2) and old_height == new_height):
break
elif (-2 < balance_factor < 2):
parent = parent.getParent()
continue # for readability
elif (balance_factor == 2):
# self.left cannot be None
left_node = parent.getLeft()
if (left_node.getBalanceFactor() == -1):
left_node.rotateLeft()
rotations_count += 1
parent = parent.rotateRight() # iterate upwards
rotations_count += 1
if (is_insert): # only one rotation at insertion
break
elif (balance_factor == -2):
# self.right cannot be None
right_node = parent.getRight()
if (right_node.getBalanceFactor() == 1):
right_node.rotateRight()
rotations_count += 1
parent = parent.rotateLeft() # iterate upwards
rotations_count += 1
if (is_insert): # only one rotation at insertion
break
else: # this should never happen
raise Exception("Balance factor is greater then 2 (in absolute value)")
if (parent != None):
parent.updateHereAndUp()
return rotations_count
def rotateLeft(self):
"""makes self the left child of self.right
@post: update help fields of the node and the child
@rtype: AVLNode
@return: the original parent of self (before rotation)
@time complexity: O(1)
"""
# prepare pointers
parent = self.getParent()
child = self.getRight()
childs_left = child.getLeft()
# rotate
childs_left.setParent(self)
self.setRight(childs_left)
self.setParent(child)
child.setLeft(self)
child.setParent(parent)
if (parent != None):
if (parent.getLeft() is self):
parent.setLeft(child)
elif (parent.getRight() is self):
parent.setRight(child)
else:
raise Exception("parent was disconnected from rotated node")
# update helpers
self.updateHelpers()
child.updateHelpers()
return parent
def rotateRight(self):
"""makes self the right child of self.left
@post: update help fields of the node and the child
@rtype: AVLNode
@return: the original parent of self (before rotation)
@time complexity: O(1)
"""
# prepare pointers
parent = self.getParent()
child = self.getLeft()
childs_right = child.getRight()
# rotate
childs_right.setParent(self)
self.setLeft(childs_right)
self.setParent(child)
child.setRight(self)
child.setParent(parent)
if (parent != None):
if (parent.getLeft() is self):
parent.setLeft(child)
elif (parent.getRight() is self):
parent.setRight(child)
else:
raise Exception("parent was disconnected from rotated node")
# update helpers
self.updateHelpers()
child.updateHelpers()
return parent
def getPredecessor(self):
"""find the predecessor of the node in the tree.
@rtype: AVLNode
@returns: predecessor of the node in the tree.
@time complexity: O(log n)
"""
return self.getSucOrPred(
hasChild=lambda x: x.hasLeft(),
getChild=lambda x: x.getLeft(),
getOtherChild=lambda x: x.getRight(),
)
def getSuccessor(self):
"""find the successor of the node in the tree.
@rtype: AVLNode
@returns: successor of the node in the tree.
@time complexity: O(log n)
"""
return self.getSucOrPred(
hasChild=lambda x: x.hasRight(),
getChild=lambda x: x.getRight(),
getOtherChild=lambda x: x.getLeft(),
)
def getSucOrPred(self, hasChild, getChild, getOtherChild):
"""logic for get successor and get predecessor.
@type hasChild: lambda AVLNode: bool
@param hasChild: check if has left or right child
@type hasChild: lambda AVLNode: AVLNode
@param hasChild: gets the same that hasChild checks
@type hasChild: lambda AVLNode: AVLNode
@param hasChild: gets the other child
@rtype: AVLNode
@returns: successor or predeccesor of the node in the tree.
@time complexity: O(log n)
"""
if hasChild(self):
node = getChild(self)
while node.isRealNode():
node = getOtherChild(node)
return node.getParent()
else:
node = self
parent = node.getParent()
while parent != None and node is getChild(parent):
node = parent
parent = parent.getParent()
return parent
class AVLTreeList(object):
""" AVLTreeList
-----------
An implementation of list ADT using AVLNodes.
@inv: for each node, abs(left.height - right.height) <= 1 # AVL
fields
------
pointers:
root: the root of the tree @type: AVLNode \n
firstNode: the first node in the list by rank @type: AVLNode \n
lastNode: the last node in the list by rank @type: AVLNode \n
helper:
size: the number of values in the tree @type: int
"""
def __init__(self, size = 0, root = AVLNode.virtualNode(), firstNode=None, lastNode=None):
"""Constructor, creates an empty list or a list from given values.
if first and last node are not given, searches them.
@type size: int
@param size: the size of the list
@type root: AVLNode
@param root: the root of the tree representing the list
@type firstNode: AVLNode
@param firstNode: the first node of the list
@type lasrNode: AVLNode
@param lasstNode: the last node of the list
@time complexity: O(log n)
"""
self.size = size
self.root = root
self.firstNode = firstNode
if firstNode == None:
self.firstNode = self.findFirstNode()
self.lastNode = lastNode
if lastNode == None:
self.lastNode = self.findLastNode()
def empty(self):
"""returns whether the list is empty
@rtype: bool
@returns: True if the list is empty, False otherwise
@time complexity: O(1)
"""
return self.getRoot() is None or not self.getRoot().isRealNode()
def retrieve(self, i):
"""retrieves the value of the i'th item in the list
@type i: int
@pre: 0 <= i < self.length()
@param i: index in the list
@rtype: str
@returns: the the value of the i'th item in the list
@time complexity: O(log n)
"""
if self.length() <= i or i < 0:
return None
node = self.getRoot()
index = i + 1
while node.isRealNode():
rank = node.getLeft().size + 1
if rank == index:
return node.getValue()
if rank > index:
node = node.left
continue
node = node.getRight()
index = (index-rank)
def retrieveNode(self, i):
"""retrieves the node of the i'th item in the list
@type i: int
@pre: 0 <= i < self.length()
@param i: index in the list
@rtype: AVLNode
@returns: the the node of the i'th item in the list
@time complexity: O(log n)
"""
node = self.getRoot()
index = i + 1
while node.isRealNode():
rank = node.getLeft().size + 1
if rank == index:
return node
if rank > index:
node = node.getLeft()
continue
node = node.getRight()
index = (index-rank)
def insert(self, i, val):
"""inserts val at position i in the list
@type i: int
@pre: 0 <= i <= self.length()
@param i: The intended index in the list to which we insert val
@type val: str
@param val: the value we inserts
@rtype: list
@returns: the number of rebalancing operation due to AVL rebalancing
@time complexity: O(log n)
"""
if self.size == 0:
self.root = AVLNode(val, None, None, 0, 1, None)
self.firstNode = self.lastNode = self.root
self.size = 1
return 0
if i == self.length():
max = self.findLastNode()
max.right = AVLNode(val, None, None, 0, 1, max)
self.size += 1
numOfRotations = max.right.rebalance(True)
self.updatePointers()
return numOfRotations
biggerNode = self.retrieveNode(i)
if not biggerNode.hasLeft():
biggerNode.left = AVLNode(val, None, None, 0, 1, biggerNode)
self.size += 1
numOfRotations = biggerNode.left.rebalance(True)
self.updatePointers()
return numOfRotations
else:
pred = biggerNode.getPredecessor()
pred.right = AVLNode(val, None, None, 0, 1, pred)
self.size += 1
numOfRotations = pred.right.rebalance(True)
self.updatePointers()
return numOfRotations
def delete(self, i):
"""deletes the i'th item in the list
@type i: int
@pre: 0 <= i < self.length()
@param i: The intended index in the list to be deleted
@rtype: int
@returns: the number of rebalancing operation due to AVL rebalancing
@time complexity: O(log n)
"""
if i >= self.length() or i < 0:
return -1
nodeToDelete = self.retrieveNode(i)
parent = nodeToDelete.getParent()
# nodeToDelete is a leaf.
if not nodeToDelete.hasRight() and not nodeToDelete.hasLeft():
return self.deleteLeaf(nodeToDelete, parent)
# nodeToDelete has only one child.
elif (not nodeToDelete.hasRight() and nodeToDelete.hasLeft()) or (nodeToDelete.hasRight() and not nodeToDelete.hasLeft()):
return self.deleteNodeWithOneChild(nodeToDelete, parent)
# nodeToDelete has two childes.
return self.deleteNodeWithTwoChild(nodeToDelete, parent)
def deleteLeaf(self, nodeToDelete, parent):
"""deletes the i'th item in the list if its a leaf
@type i: int
@pre: 0 <= i < self.length()
@param i: The intended index in the list to be deleted
@rtype: int
@returns: the number of rebalancing operation due to AVL rebalancing
@time complexity: O(log n)
"""
virtNode = AVLNode.virtualNode(parent)
if parent == None:
nodeToDelete = virtNode
self.size -= 1
self.root = self.firstNode = self.lastNode = nodeToDelete
return 0
elif parent.getRight() is nodeToDelete:
parent.right = virtNode
numOfRotations = parent.getRight().rebalance()
else:
parent.left = virtNode
numOfRotations = parent.getLeft().rebalance()
self.size -= 1
self.updatePointers()
return numOfRotations
def deleteNodeWithOneChild(self, nodeToDelete, parent):
"""deletes the i'th item in the list if it has only one child
@type i: int
@pre: 0 <= i < self.length()
@param i: The intended index in the list to be deleted
@rtype: int
@returns: the number of rebalancing operation due to AVL rebalancing
@time complexity: O(log n)
"""
if not nodeToDelete.hasRight() and nodeToDelete.hasLeft():
if parent is None:
self.root = nodeToDelete.getLeft()
nodeToDelete.getLeft().parent = parent
else:
if parent.getRight() is nodeToDelete:
parent.setRight(nodeToDelete.getLeft())
else: # parent.left is nodeToDelete
parent.setLeft(nodeToDelete.getLeft())
nodeToDelete.getLeft().parent = parent
numOfRotations = nodeToDelete.getLeft().rebalance()
self.size -=1
self.updatePointers()
return numOfRotations
elif nodeToDelete.hasRight() and not nodeToDelete.hasLeft():
if parent is None:
self.root = nodeToDelete.getRight()
nodeToDelete.getRight().parent = parent
else:
if parent.getRight() is nodeToDelete:
parent.setRight(nodeToDelete.getRight())
else: # parent.left is nodeToDelete
parent.setLeft(nodeToDelete.getRight())
nodeToDelete.getRight().parent = parent
numOfRotations = nodeToDelete.getRight().rebalance()
self.size -=1
self.updatePointers()
return numOfRotations
def deleteNodeWithTwoChild(self, nodeToDelete, parent):
"""deletes the i'th item in the list if it has 2 childs
@type i: int
@pre: 0 <= i < self.length()
@param i: The intended index in the list to be deleted
@rtype: int
@returns: the number of rebalancing operation due to AVL rebalancing
@time complexity: O(log n)
"""
successor = nodeToDelete.getSuccessor()
successorParent = successor.getParent()
# replace with the successor
nodeToDelete.setValue(successor.getValue())
# delete the successor
if successor.hasRight():
return self.deleteNodeWithOneChild(successor, successorParent)
else: # successor is a leaf
return self.deleteLeaf(successor, successorParent)
def first(self):
"""returns the value of the first item in the list
@rtype: str
@returns: the value of the first item, None if the list is empty
@time complexity: O(1)
"""
if self.size == 0:
return None
return self.firstNode.value
def last(self):
"""returns the value of the last item in the list
@rtype: str
@returns: the value of the last item, None if the list is empty
@time complexity: O(1)
"""
if self.size == 0:
return None
return self.lastNode.value
def findFirstNode(self):
"""find the first node in the tree by repeatedly going left.
@pre: self.length > 0
@rtype: AVLNode
@returns: the first node in the tree.
@time complexity: O(log n)
"""
node = self.root
while node.isRealNode():
node = node.left
return node.parent
def findLastNode(self):
"""find the last node in the tree by repeatedly going right.
@pre: self.length > 0
@rtype: AVLNode
@returns: the last node in the tree.
@time complexity: O(log n)
"""
node = self.root
while node.isRealNode():
node = node.right
return node.getParent()
def listToArray(self):
"""returns an array representing list
@rtype: list
@returns: a list of strings representing the data structure
@time complexity: O(n)
"""
if self.size == 0:
return []
current = self.getRoot()
stack = []
result = [0] * self.size
i = 0
while True:
if current.isRealNode():
stack.append(current)
current = current.getLeft()
elif(stack):
current = stack.pop()
result[i] = current.getValue()
current = current.getRight()
i += 1
else:
break
return result
@staticmethod
def arrayToList(arr):
""" Turns arr to a list
@type arr: list
@param arr: array to turn into a list
@time complexity: O(n)
"""
def arrToList_rec(arr, start, end, parent):
""" act as if arr is from start (inclusive)
to end (not inclusive).
@time complexity: O(n)
"""
if start >= end:
return AVLNode.virtualNode(parent)
mid = start + (end - start)//2
root = AVLNode(arr[mid], parent=parent)
left = arrToList_rec(arr, start, mid, root)
right = arrToList_rec(arr, mid+1, end, root)
root.setLeft(left)
root.setRight(right)
root.updateHelpers()
return root
if len(arr) == 0:
return AVLTreeList(0)
lst_root = arrToList_rec(arr, 0, len(arr), None)