We had two hours of lecture about how to represent binary trees in Python. Since the writing class for "binary tree" is similar to stack, class (which we covered until now during lectures), "binary tree" should not too challenging to me.
Here is the code given for the lecture, as we can see from the body of __init__ function
def __init__(self: 'BTNode', data: object,
left: 'BTNode'=None, right: 'BTNode'=None) -> None:
"""Create BT node with data and children left and right."""
self.data, self.left, self.right = data, left, right
However the difference is also found here: the code is written in just one line, different from what we had before.
I think the nicest about binary trees is that it is a great example for doing recursion since a parent tree can have several children(sometimes no child) and then keep continuing. If we know something about its subtrees, let's say leaves, then we know the number of leaves of the whole binary trees.
def __repr__(self):
''' (BTNode) -> str
Represent BTNode (self) as a string that can be evaluated to
produce an equivalent BTNode.
>>> BTNode(1, BTNode(2), BTNode(3))
BTNode(1, BTNode(2, None, None), BTNode(3, None, None))
'''
return 'BTNode({}, {}, {})'.format(repr(self.data),
repr(self.left),
repr(self.right))
In __repr__ method, repr, itself is used three times in the body lines (this is called as recursion).
The professor, heap covered three examples of how to order binary trees (preorder, inorder, and postorder). All of three functions involve recursion, and I find it really helpful to run the recursive functions in Python visualizer. It can help you understand recursion better.
Also, heap talked about Tree class, the most interesting of this class is basically all of its method involve recursion. So when he wrote the method, I experienced a hard to follow him. (also one-line-coding was difficult) But I did review all the methods at home and looked again the lab which is related to "binary tree". For the method called, 'descendents_from_list,' the last three lines were confusing even though I wrote down the examples step by step followed by the body of the code. I visited help center in BA, to get some help, and now I feel confident for all methods in btnode.
def descendents_from_list(t, L, arity):
''' (Tree, list, int) -> Tree
Populate t's descendents from L, filling them
in in level order, with up to arity children per node.
Then return t.
>>> descendents_from_list(Tree(0), [1, 2, 3, 4], 2)
Tree(0, [Tree(1, [Tree(3), Tree(4)]), Tree(2)])
'''
q = Queue()
q.enqueue(t)
L = L.copy()
while not q.is_empty(): # unlikely to happen
new_t = q.dequeue()
for i in range(0,arity):
if len(L) == 0:
return t # our work here is done
else:
new_t_child = Tree(L.pop(0))
new_t.children.append(new_t_child)
q.enqueue(new_t_child)
return t
No comments:
Post a Comment