Repository navigation
Expand file tree
/
Copy pathAVLTree.py
More file actions
1528 lines (604 loc) · 27 KB
/
Copy pathAVLTree.py
File metadata and controls
1528 lines (604 loc) · 27 KB
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
"""A class represnting a node in an AVL tree"""
import random
class AVLNode(object):
"""Constructor, you are allowed to add more fields.
@type key: int
@param key: key of your node
@type value: string
@param value: data of your node
"""
def __init__(self, key, value, parent = None ): #complexity O(1) - max one recursive call
self.key = key
self.value = value
self.parent = parent
if key == None: #if key in None- a virtual node is created and the recursion stops
self.height = -1
self.left = None
self.right = None
if key != None : #A real node
self.left = AVLNode (None, None, self) #recursively creates a virtual node
self.right = AVLNode (None, None, self) #recursively creates a virtual node
self.height = 1 + max(self.left.height, self.right.height)
self.BF = ( self.left.height - self.right.height)
''' preforms a right rotation on the node and its left child
comlexity: O(1)'''
def rightrotate(self):
LeftChild= self.left
self.left = LeftChild.right #update the new left child of the original node to be the right child of its original left child
LeftChild.right.parent = self #Update the parent pointer of the right child of the original left child.
LeftChild.right = self #update the new right child of the original left child
LeftChild.parent=self.parent #Update the parents pointers
self.parent =LeftChild #Update the parents pointers
self.height = max(self.left.height, self.right.height) + 1 # update self's height
LeftChild.height = max(LeftChild.left.height, LeftChild.right.height) + 1
return LeftChild
''' preforms a left rotation on the node and its right child
complexity: O(1)'''
def leftrotate(self):
Rightchild= self.right
self.right = Rightchild.left #update the new right child of the original node to be the left child of its original right child
Rightchild.left.parent = self #Update the parent pointer of the left child of the original right child.
Rightchild.left = self #update the new left child of the original right child
Rightchild.parent=self.parent #Update the parents pointers
self.parent = Rightchild #Update the parents pointers
self.height = max(self.left.height, self.right.height) + 1 # update self's height
Rightchild.height = max(Rightchild.left.height, Rightchild.right.height) + 1
return Rightchild
"""Finds the successor of the node in an in-order traversal.
@ precondition: will not be used on the maximal node
Complexity: O(log(n)) in a balanced AVL tree.
"""
def successor(self):
currnode = self
if currnode.right.is_real_node(): # if a right subtree exists - find the minimum of the right subtree
currnode = currnode.right
while currnode.left.is_real_node():
currnode = currnode.left
else : # there is no right subtree - find the first node that we turn right to get to while going up the tree.
while currnode.parent and currnode == currnode.parent.right :
currnode = currnode.parent
currnode=currnode.parent
return currnode
"""Finds the predecessor of the node in an in-order traversal.
@ precondition: will not be used on the miniimal node
Complexity: O(log(n)) in a balanced AVL tree.
"""
def predecessor(self):
currnode = self
if currnode.left.is_real_node(): # if a left subtree exists - find the maximum of the left subtree
currnode = currnode.left
while currnode.right.is_real_node():
currnode = currnode.right
else : # there is no left subtree - find the first node that we turn left to get to while going up the tree.
while currnode.parent and currnode == currnode.parent.left :
currnode = currnode.parent
currnode=currnode.parent
return currnode
"""returns whether self is not a virtual node
@rtype: bool
@returns: False if self is a virtual node, True otherwise.
"""
def is_real_node(self): #if key is None- node is not real, if key != None- node is real
return self.key != None
''' replace a node with a given node, keeping the originals node parents and children O(1)'''
def replace(self, other):
other.left = self.left
other.right = self.right
other.right.parent = other
other.left.parent = other
other.parent = self.parent
other.height = self.height
if self.parent : #self is not the root
if self.parent.right == self : #self is a right child
self.parent.right = other
elif self.parent.left == self : #self is a right child
self.parent.left = other
"""
A class implementing an AVL tree.
"""
class AVLTree(object):
"""
Constructor, you are allowed to add more fields.
"""
def __init__(self):
self.root = None
self.size_value = 0
self.maxnode = None
"""Balances the subtree rooted at the given node.
Complexity: O(1) per rotation
@type node: AVLNode
@param node: The node to balance.
@rtype: AVLNode
@returns: The new root of the balanced subtree.
"""
def balance(self,node):
bf = node.left.height - node.right.height
firstparent = node.parent
if bf == -2:
if node.right.BF == -1 or node.right.BF == 0 :
nextnode = node.leftrotate()
else:
node.right = node.right.rightrotate() #explanation in documentation
nextnode = node.leftrotate()
elif bf == 2:
if node.left.BF == 1 or node.left.BF ==0 :
nextnode = node.rightrotate()
else:
node.left = node.left.leftrotate() #explanation in documentation
nextnode = node.rightrotate()
# else:
# nextnode = node
if node == self.root:
self.root=nextnode
if firstparent:
if node == firstparent.right:
firstparent.right = nextnode
nextnode.parent = firstparent
else:
firstparent.left =nextnode
nextnode.parent = firstparent
return nextnode
"""searches for a node in the dictionary corresponding to the key (starting at the root)
@type key: int
@param key: a key to be searched
@rtype: (AVLNode,int)
@returns: a tuple (x,e) where x is the node corresponding to key (or None if not found),
and e is the number of edges on the path between the starting node and ending node+1.
"""
# complexity = O(log(n)), the height of an AVL tree is O(logn(n))
def search(self, key):
edges = 0
currnode = self.root
while currnode.is_real_node(): # preforming a "binary search" on the tree while there are still more nodes
if currnode.key == key:
return (currnode, edges + 1)
elif currnode.key > key: # currnode.key is bigger - we need to go left
currnode = currnode.left
edges += 1
elif currnode.key < key: # currnode.key is smaller - we need to go right
currnode = currnode.right
edges += 1
return None, edges
"""searches for a node in the dictionary corresponding to the key, starting at the max
@type key: int
@param key: a key to be searched
@rtype: (AVLNode,int)
@returns: a tuple (x,e) where x is the node corresponding to key (or None if not found),
and e is the number of edges on the path between the starting node and ending node+1.
Complexity: O(log(n))
"""
def finger_search(self, key):
currnode = self.max_node() #starting at the max node
edges = 0
# Traverse up the tree while the key might be in the subtree of an ancestor
while (currnode.parent) and (key < currnode.key) and ( key <= currnode.parent.key) :
currnode = currnode.parent
edges += 1
# If the current node has the key, return it
if currnode.key == key:
return (currnode, edges +1)
# Otherwise, search in the left subtree
if key < currnode.key:
while currnode.is_real_node(): # preforming a "binary search" on the tree while there are still more nodes
if currnode.key == key:
return (currnode, edges + 1)
elif currnode.key > key: # currnode.key is bigger - we need to go left
currnode = currnode.left
edges += 1
elif currnode.key < key: # currnode.key is smaller - we need to go right
currnode = currnode.right
edges += 1
return None , edges
"""inserts a new node into the dictionary with corresponding key and value (starting at the root)
@type key: int
@pre: key currently does not appear in the dictionary
@param key: key of item that is to be inserted to self
@type val: string
@param val: the value of the item
@rtype: (AVLNode,int,int)
@returns: a 3-tuple (x,e,h) where x is the new node,
e is the number of edges on the path between the starting node and new node before rebalancing,
and h is the number of PROMOTE cases during the AVL rebalancing
complexity: O(logn) - searching for the insertion location- O(logn)
+ going up the the tree - O(logn)
at each node in the way O(1)- the function "balance" is O(1)
"""
def insert(self, key, val):
currnode = self.get_root()
self.size_value += 1
if currnode == None : #the tree is empty
self.root = AVLNode(key, val)
self.maxnode = self.root # the only node is also the maximal node
return self.root , 0 , 0
if self.maxnode == None:
while currnode.right.is_real_node():
currnode=currnode.right
self.maxnode = currnode
currnode=self.get_root()
edges = 0
while currnode.is_real_node(): #find the insert location
parent = currnode
if currnode.key < key :
currnode = currnode.right
else:
currnode = currnode.left
edges += 1
#currnode is the place we will insert the new node into
if parent.right == currnode: #the inserted node will need to be the right child of the parent
parent.right = AVLNode (key,val, parent)
if parent.right.key > self.maxnode.key: # the only time we need to check since that if it is the left child it is not the maximal node
self.maxnode = parent.right
else: #the inserted node will need to be the left child of the parent
parent.left = AVLNode (key,val, parent)
promotions = 0
while parent: #while we haven't got to the root
parent.BF = parent.left.height - parent.right.height
currBF = parent.BF
if currBF == 0: #if so' the tree if a valid AVL Tree and we're done!
return currnode, edges, promotions
elif currBF == 1 or currBF == -1 : #promote the parent and move onto his parent
new_height = max(parent.left.height, parent.right.height) + 1
if new_height > parent.height: # Count promotion only if height actually increases
promotions += 1
parent.height = new_height
parent = parent.parent
else: #Bf = -2/2, the helper function balance will balance the node's subtree and return the new subtree's root
parent = self.balance(parent)
parent=parent.parent
return currnode, edges, promotions
"""inserts a new node into the dictionary with corresponding key and value, starting at the max
@type key: int
@pre: key currently does not appear in the dictionary
@param key: key of item that is to be inserted to self
@type val: string
@param val: the value of the item
@rtype: (AVLNode,int,int)
@returns: a 3-tuple (x,e,h) where x is the new node,
e is the number of edges on the path between the starting node and new node before rebalancing,
and h is the number of PROMOTE cases during the AVL rebalancing
complexity: O(logn) - same as insert - the search part might be longer but still bounded O(logn).
"""
def finger_insert(self, key, val):
currnode = self.maxnode
self.size_value += 1
if currnode == None : #the tree is empty
self.root = AVLNode(key, val)
self.maxnode = self.root #the only node is also the maximal node
return self.root , 0 , 0
edges = 0
while (currnode.parent) and (key < currnode.key) and key < currnode.parent.key: # searching for the insert place like in finger_search
currnode = currnode.parent
edges += 1
while currnode.is_real_node():
parent = currnode
if currnode.key < key :
currnode = currnode.right
else:
currnode = currnode.left
edges += 1
#currnode is where we would insert our new node, parent is his parent
if parent.right == currnode: #we need to insert the node to be the right child of the parent
parent.right = AVLNode (key,val, parent)
if parent.right.key > self.maxnode.key: # the only time we need to check since that if it is the left child it is not the maximal node
self.maxnode = parent.right
else: #we need to insert the node to be the left child of the parent
parent.left = AVLNode (key,val, parent)
promotions = 0
while parent: #same explaination as the one in "insert"
parent.BF = parent.left.height - parent.right.height
currBF = parent.BF
if currBF == 0: #if so' the tree if a valid AVL Tree and we're done!
return currnode, edges, promotions
elif currBF == 1 or currBF == -1 :
new_height = max(parent.left.height, parent.right.height) + 1
if new_height > parent.height: # Count promotion only if height actually increases
promotions += 1
parent.height = new_height
parent = parent.parent
else:
parent = self.balance(parent)
parent=parent.parent
return currnode, edges, promotions
"""deletes node from the dictionary
@type node: AVLNode
@pre: node is a real pointer to a node in self
"""
def delete(self, node):
self.size_value -= 1
delnode= node #the node to be deleted
if self.size_value==0:
self.root=None
self.maxnode = None
return
if delnode == self.maxnode: #in this case we need to update maxnode to be his predecessor.
self.maxnode = self.maxnode.predecessor()
if node.right.is_real_node() and node.left.is_real_node() : #if the node has two children we need to replace it with his successor and delete his successor
delnode = node.successor() # note that if the node has two children it is not the maxnode so we can call successor
node.replace(delnode)
father = delnode.parent
if delnode.right.is_real_node() or delnode.left.is_real_node() : #delnode has *exactly* one child
#in this case, father adopts delnode's child
if delnode.left.is_real_node():
child = delnode.left
else:
child = delnode.right
if father == None:
self.root = child
return
if father.left==delnode:
father.left=child
child.parent = father
else:
father.right=child
child.parent = father
else: # delnode doesn't have any children (is a leaf)
#turn delnode into a virtural node
if father.right == delnode:
father.right = AVLNode(None,None,father)
else:
father.left = AVLNode(None,None, father)
while father: #same as balancing in insert and finger_insert
prevheight = father.height
father.BF = father.left.height - father.right.height
currBF = father.BF
if currBF == 0:
father.height = max(father.left.height, father.right.height) + 1
if father.height == prevheight:
return #we can stop
father = father.parent
elif currBF == 1 or currBF == -1 :
father.height = max(father.left.height,father.right.height)+1 #update height
if father.height == prevheight:
return #we can stop
father = father.parent
else:
father = self.balance(father)
father=father.parent
return
"""joins self with item and another AVLTree
@type tree2: AVLTree
@param tree2: a dictionary to be joined with self
@type key: int
@param key: the key separting self and tree2
@type val: string
@param val: the value corresponding to key
@pre: all keys in self are smaller than key and all keys in tree2 are larger than key,
or the opposite way
"""
def join(self, tree2, key, val):
# If one of the trees is empty, add the key and value to the other tree
if (tree2.root == None): # If tree2 is empty
self.insert(key, val) # Insert the key and value into the current tree (self)
tree2.root = None # No need for tree2's root anymore, as it is now empty
# If tree 'self' is empty, transfer all values from tree2 to tree 'self'
elif (self.root == None): # If self tree is empty
tree2.insert(key, val) # Insert the key and value into tree2
self.root = tree2.root # Transfer tree2's root to self
self.maxnode = tree2.maxnode
tree2.root = None # Now tree2 is empty
# If both trees are non-empty, we need to join them
else: # If both trees are non-empty
newnode = AVLNode(key, val) # Create a new node with the provided key and value
minheight = min(self.root.height, tree2.root.height) # Find the minimum height of the two roots
# If the height of self's root is greater than the minimum height, start the join from tree 'self'
if self.root.height > minheight: # If the height of self's root is greater than the minimum height
node=self.root
if self.root.key < key:
self.maxnode = tree2.maxnode