I'm dealing with a Generic Tree I'm representing in this way:
class GenericTree:
""" A tree in which each node can have any number of children.
Each node is linked to its parent and to its immediate sibling on the right
"""
def __init__(self, data):
self._data = data
self._child = None
self._sibling = None
self._parent = None
And I have to mirror it, and recursion is allowed. I solved it in this way:
def mirror(self):
""" Modifies this tree by mirroring it, that is, reverses the order
of all children of this node and of all its descendants
- MUST work in O(n) where n is the number of nodes
- MUST change the order of nodes, NOT the data (so don't touch the data !)
- DON'T create new nodes
- It is acceptable to use a recursive method.
Example:
a <- Becomes: a
├b ├i
│├c ├e
│└d │├h
├e │├g
│├f │└f
│├g └b
│└h ├d
└i └c
"""
mylist=[] #Initializing a list
if self._child: #If GenTree has children:
current=self._child #initalizing the variable for the while loop
while current: #until there are root's sons
mylist.append(current) #I put it them in the list
current=current._sibling #Going ahead to put all the sons in the list
self._child=mylist[-1] #The _child is now the "rightest" one, i.e. the son that points to None
#Now I iterate within the list in the opposite direction:
for i in range(-len(mylist),0):
mylist[i]._sibling=mylist[i+1] if i<-1 else None #I go from right to left #and I reverse in this way the sense of the list (if the sons were ROOT|->a->b->c, now they should be ROOT|->c->b->a
for i in range(-len(mylist),0):
mylist[i].mirror() #Doing the recursion for each son using them as roots
But It's not working: Here's an example of an error generated by my code:
AssertionError: Children sizes are different !
ACTUAL EXPECTED
a a
├b ├b
│└d │├d <--- DIFFERENT !
└e │└c
└e
What am I doing wrong?