Link Length
Write a function in Python that mutates a tree t
so that it is "reflected" over its center.
def reflect(t):
"""
>>> tree = Tree(3, [Tree(4, [Tree(5), Tree(6)]), Tree(7)])
>>> reflect(tree)
>>> tree
Tree(3, [Tree(7, [Tree(6), Tree(5)]), Tree(4)])
"""
### Your Code Here
Here's a visual representation of the doctest:
Toggle Solution
def reflect(t):
t.children = t.children[::-1]
for child in t.children:
reflect(child)
For this problem, we're mutating t
, which is why we directly modify t.children
rather than constructing and returning a new tree. In this case, we set the list t.children
to a copy of t.children
that is reversed (which is what the [::-1]
means).
After that, we want to iterate through each of t
's children and recursively call reflect on them to work our way down the tree.