## Trees: Conceptual **Solutions**

### Code Writing

Write out a function that will sum up all of the labels in a tree (assume that all labels are ints)

def sum_labels(t):

>>> t = Tree(5, [Tree(1, [Tree(2, [Tree(3)])])])

>>> sum_labels(t)

11

if **t.is_leaf()**:

return **t.label**

return **sum([sum_labels(b) for b in t.branches]) + t.label**

Write out a function that takes in a tree and a value and return true if n is in the tree and false if it is not.

def is_here(t, n):

>>> t = Tree(5, [Tree(2), Tree(1, [Tree(2, [Tree(3)])])])

>>> is_here(t, 3)

True

if **t.is_leaf():**

return **t.label == n**

return **t.label == n or any([is_here(b, n) for b in t.branches])**

Write out a function that will take in a tree and return a new tree that is identical in structure as the given parameter t, but the value of each node is doubled.

def double(t):

>>> t = Tree(5, [Tree(2), Tree(1, [Tree(2, [Tree(3)])])])

>>> double(t)

Tree(10, [Tree(4), Tree(2, [Tree(4, [Tree(6)])])])

>>> t

Tree(5, [Tree(2), Tree(1, [Tree(2, [Tree(3)])])])

if **t.is_leaf():**:

return **Tree(t.label * 2)**

branches = **[double(b) for b in t.branches]**

return Tree(**t.label * 2, branches**)

Write out a function that will take in a tree and double the value of every node in the tree (and this time, do it mutatively).

def double_mutative(t):

>>> t = Tree(5, [Tree(2), Tree(1, [Tree(2, [Tree(3)])])])

>>> double(t)

Tree(10, [Tree(4), Tree(2, [Tree(4, [Tree(6)])])])

>>> t

Tree(10, [Tree(4), Tree(2, [Tree(4, [Tree(6)])])])

t.label = **t.label * 2**

if **t.is_leaf():**

return **t**

t.branches = **[double_mutative(b) for b in t.branches]**

return t