Skip to content

Commit c93985e

Browse files
committed
Update TreeMap.py
Balanced Tree rotations and Trinode restructuring implementation.
1 parent de2e407 commit c93985e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

BinarySearchTrees/TreeMap.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,51 @@ def __delitem__(self, k):
209209
self._rebalance_access(p)
210210

211211
raise KeyError("Key Error: "+ repr(k))
212+
213+
######### Search Tree Balacing Algorithms for (AVL, Splay Tree, RedBlack Trees) not used by this class, but implemented here for inheritance ######
214+
215+
def _relink(self, parent, child, make_left_child):
216+
"""Relink aprent node with child node (we allow child to be None)"""
217+
218+
if make_left_child:
219+
parent._left = child #make it a left child
220+
else:
221+
parent._right = child # make it a right child
222+
223+
if child is not None:
224+
child._parent = parent # make child point to parent
225+
226+
def _rotate(self, p):
227+
"""rotate position p above its parent"""
228+
x = p._node
229+
y = x._parent #assume this exists
230+
z= y._parent # grand parent
231+
232+
if z is None:
233+
self._root = x #x becomes root if grand parent z is None
234+
x._parent = None
235+
else:
236+
self._relink(z,x, y == z._left) # x becomes a direct child of z
237+
238+
# now rotate x and y, including transfer of middle subtree
239+
if x == y._left:
240+
self._relink(y, x._right, True) # x._right becomes left child of y
241+
self._relink(x, y, False)
242+
else:
243+
self._relink(y, x._left, False) # x._left becomes right child of y
244+
self._relink(x , y, True) # Y becomes left child of x
245+
246+
def _restructure(self, x):
247+
"""Perform Trinode Restructuring of Position x with parent/grandparent"""
248+
249+
y= self.parent(x)
250+
z = self.parent(y)
251+
252+
if (x == self.right(y)) == (y== self.right(z)): #matching alignments
253+
self._rotate(y) #single rotation
254+
return y # y is the new subtree root
255+
else:
256+
self._rotate(x) #double rotation
257+
self._rotate(x)
258+
259+
return x

0 commit comments

Comments
 (0)