Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the function mirrorTree() to take in a root node of a tree and return a

ID: 3711306 • Letter: C

Question

Complete the function mirrorTree() to take in a root node of a tree and return another copy of the tree that is a mirror of the original one. Your function cannot modify the tree that is passed in.

This will require you to use a helper function with recursion. I have already gotten you started with the helper.

An example of a mirrored tree is shown below:

CODE:

class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
  
def mirrorTree(root):
new_root = Node(root.value)
assign_tree(root, new_root)
return new_root
  
def assign_tree(old_root, new_root):
# this helper will recursively assign the left subtree
# of old_root to be the right subtree of new_root
# and assign the right subtree of old_root to be the
# left subtree of new_root?

I nstructions from your teacher 1 class Node: 2 def init (self, value) Problem self.value value self.left None self.right None Complete the function mirrorTree() to take in a root node of a tree and return another copy of the tree that is a mirror of the original one. Your function cannot modify the tree that is passed in 7 def mirrorTree(root) This will require you to use a helper function with recursion. I have already gotten you started with the helper new-root = Node(root . value) 9 assign treeCroot, new_root) return new_root 10 An example of a mirrored tree is shown below 12 def assign tree(old_root, new_root): 13 14 15 # and assign the right subtree of old-root to be the 16 # left subtree of new-roo # this helper will recursively assign the left subtree # of old-root to be the right subtree of new-root Mirror Trees

Explanation / Answer

def assign_tree(oldroot, newroot):
    if oldroot is None:
        return
    #the below line will exchange nodes
    newroot.left, newroot.right = oldroot.right, oldroot.left
    #for every left call on oldroot we will call right call on new root
    assign_tree(oldroot.left,newroot.right)
    assign_tree(oldroot.right,newroot.left)