#Constructor
def tree(label, branches=[]):
for branch in branches:
assert is_tree(branch)
return [label] + list(branches)
#Selectors
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return false
return True
def is_leaf(tree):
return not branches(tree)
def print_tree(t, indent=0):
print(' ' * indent + str(label(t)))
for b in branches(t):
print_tree(b, indent + 1)
Write a function that takes in a tree and doubles every value. It should return a new tree. You can assume that every item is a number. Using the tree above
def double_tree(t): """Return a tree with the square of every element in t >>> numbers = tree(1, [tree(2, [tree(3), tree(4)]), tree(5, [tree(6, [tree(7)]), tree(8)])]) >>> print_tree(double_tree(numbers)) 2 4 6 8 10 12 14 16 """ |
CODE:
class node: #assuming node contain 3 fields- value, left and right
def_ init_(self, val): this.value = Val this.left= this.right = none
def double_tree(t): #t is the root node of tree if t == none: return #empty tree t.value = 2*t.value #double root value double_tree(t.left) # recursive call on left subtree double_tree(t.right) #recursive call on right subtree
Get Answers For Free
Most questions answered within 1 hours.