This is my implementation of the two functions. How do I combine the toNextBlackLevel, balancedTree
in endgame
?
# Provided code to support Task 4:
def toNextBlackLevel(self, node):
# inspect subtree down to the next level of blacks
# and return list of components (subtrees or nodes) in L-to-R order
# (in cases of interest there will be 7 components A,a,B,b,C,c,D).
if colourOf(node.left) == Black: # node.left may be None
leftHalf = [node.left]
else:
leftHalf = self.toNextBlackLevel(node.left)
if colourOf(node.right) == Black:
rightHalf = [node.right]
else:
rightHalf = self.toNextBlackLevel(node.right)
return leftHalf + [node] + rightHalf
def balancedTree(self, comps):
# build a new (balanced) subtree from list of 7 components
[A, a, B, b, C, c, D] = comps
a.colour = Red
a.left = A
a.right = B
c.colour = Red
c.left = C
c.right = D
b.colour = Black
b.left = a
b.right = c
return b
# TODO: Task 4.
# endgame(self)
# hat inspects the tree to see what needs to be done, and applies the appropriate action to turn it into a legal red-black tree. The provided functions toNextBlackLevel and balancedTree are there to help you in the case where some local re-balancing is called for
def endgame(self):
# inspect subtree down to the next level of blacks
# and return list of components (subtrees or nodes) in L-to-R order
# (in cases of interest there will be 7 components A,a,B,b,C,c,D).
if colourOf(self.root.left) == Black: # node.left may be None
leftHalf = [self.root.left]
else:
leftHalf = self.toNextBlackLevel(self.root.left)
if colourOf(self.root.right) == Black:
rightHalf = [self.root.right]
else:
rightHalf = self.toNextBlackLevel(self.root.right)
comps = leftHalf + [self.root] + rightHalf
self.root = self.balancedTree(comps)
# insert(self,key,value)
def insert(self, key, value):
self.plainInsert(key, value) # insert the new node
self.repeatRedUncle() # apply the red uncle rule as often as possible
self.endgame() # apply the endgame rule
# Provided code:
# Printing tree contents
def __str__(self, x):
if x == None:
return 'None:B'
else:
leftStr = '[ ' + self.__str__(x.left) + ' ] '
rightStr = ' [ ' + self.__str__(x.right) + ' ]'
return leftStr + x.__str__() + rightStr
def __repr__(self):
return self.__str__(self.root)
def showStack(self):
return [x.__str__() if isinstance(x, Node) else branchLabels[x]
for x in self.stack]
# All keys by left-to-right traversal
def keysLtoR_(self, x):
if x == None:
return []
else:
return self.keysLtoR_(x.left) + [x.key] + self.keysLtoR_(x.right)
def keysLtoR(self):
return self.keysLtoR_(self.root)