class Node: def __init__(self, value): self.value = value self.left = None self.
ID: 3711448 • Letter: C
Question
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
Explanation / Answer
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):
# if the current old tree is not empty
if old_root != None:
# et the value of new_root same as old_root
new_root.value = old.value
# if there is no left child in old_root
if old_root.left == None:
new_root.right = None
else:
# create a temporary node as the right node
new_root.right = Node(1)
# traverse the left subtree
assign_tree( old_root.left , new_root.right )
# if there is no right child in old_root
if old_root.right == None:
new_root.left = None
else:
# create a temporary node as the right node
new_root.left = Node(1)
# traverse the riht subtree
assign_tree( old_root.right , new_root.left )
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.