Trees, Mutation, Nonlocal
annietang@berkeley.edu�anniewtang.github.io/cs61a
links.cs61a.org/annie-disc
Trees!
Super important, and recurring!
(also recursive)
BUT FIRST . . .
a meme :—)
Terminology
branches: the subtree that extends from the branch node
Terminology
Trees are an Abstract Data Type
(a Concept™ that you choose the implementation for)
Implementation
def tree(label, branches=[]):� # returns a Tree of some form
ABSTRACTION!!
Implementation
def label(tree):� # returns the label of your root node in the Tree�def branches(tree):� # returns the branches in your Tree�def is_leaf(tree):� # tells you if a node is a leaf or not
ABSTRACTION!!
Tree Construction Practice
Tree(1, [Tree(3,� [Tree(4), � Tree(5), � Tree(6)]),
Tree(2)])
Why Recursion?
Why Recursion? (pt2)
Practice Problem 3.2
def tree_max(t):
return max([label(t)] + [tree_max(b) for b in branches(t)]
use RECURSION!
3.2, 3.3
3.3 square(t)
3.2: height(t)
discuss w/your neighbors!
3.4: find_path(tree, x)
discuss w/your neighbors!
Nonlocal
General Idea
Things to Remember
Mutable Lists
General Idea
General Idea
Have some box-and-pointer diagrams.
Motivation
why we do this thing
How to draw these things!!??
optional: label each box with the indice
(!) the arrow points to the object as a whole, not at a specific box!
>>> basic = [1, 2, 3]
>>> nested = [61, [‘a’], ‘!’]
Q: what do nested lists look like?
A: “nested” pointer!!
1
2
3
basic
61
‘a’
nested
‘!’
Alright, let’s go back to python!
Some pretty nifty functions
lst.append(element)
lst = [1. 2]
lst.extend(iterable)
lst = [1. 2]
brief interlude: extend vs. append
brief interlude 2: += vs. =
also, += is the same as extend!
lst.insert(index, elem)
lst = [1. 2]
lst.remove(element)
lst = [1. 2]
lst.pop(index)
i.e. will remove last element if you just do .pop()
>>> lst.pop()�2�>>> lst�[1]
>>> lst.extend([2, 3])�>>> lst�[1, 2, 3]�>>> lst.pop(1)�2�>>> lst�[1, 3]
lst = [1. 2]