This is a general tree implementation from the lecture slide:
class Tree:
’’’ Represent a Bare-bones Tree ADT’’’
def __init__(self, value=None, children=None):
’’’ (Tree, object, list) -> NoneType
Create Tree(self) with root node value
and 0 or more children.
’’’
self.value = value
# copy children if not None
self.children = children.copy() else []
# the functional if on the line above is equivalent to :
# if not children:
#self.children = []
#else:
#self.children = children.copy()
From this class Tree, we
can find the height of the tree, find how many leaves, and the arity of the
tree T by using def---.
For me, counting leaves were a bit confusing. But I found a way of doing it. If there were a method:
def list_leaves(t):
'''
(Tree) -> list
Return a list of values in leaves of t.
>>> t = Tree(0)
>>> list_leaves(t)
[0]
>>> t = descendents_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7,
8], 3)
>>> L = list_leaves(t)
>>> L.sort() # so list is predictable to compare
>>> L
[3,
4, 5, 6, 7, 8]
'''
I would first look at the arity, which in this case is 3, next to the eight numbers in a list. This means on the top of the list below 0, there will be three numbers. Therefore it'll look like:
0
1 2 3
1 2 3
Then below each '1', '2', and '3', there also will be 3 children.
0
1 2 3
4 5 6 7 8
Therefore, [3,4,5,6,7,8] will be the leaf because they do not have any children.