On last week, week 9, we had term test 2 and 35 minutes of lecture, and it was about two new methods of binary search tree, 'insert' and 'delete'.
The complete version of function insert is
def insert(node, data):
''' (BTNode, object) -> BTNode
Insert data in BST rooted at node if necessary, and return new root.
>>> b = BTNode(8)
>>> b = insert(b, 4)
>>> b = insert(b, 2)
>>> b = insert(b, 6)
>>> b = insert(b, 12)
>>> b = insert(b, 14)
>>> b = insert(b, 10)
>>> print(b)
14
12
10
8
6
4
2
<BLANKLINE>
'''
return_node = node
if not node:
return_node = BTNode(data)
elif data < node.data:
node.left = insert(node.left, data)
elif data > node.data:
node.right = insert(node.right, data)
else: # nothing to do
pass
return return_node
As we can notice from the above, the function 'insert' is basically creating 'a new binary tree,' then insert data in corresponding position (this is based on the size of number).
so if nothing in tree yet, we just add data -> return_node = BTNode(data)
if data is existed, and new data is bigger than datas in node ->
node.right = insert(node.right, data).
The importance of this code is 'recursion'.
On both data < node.data and data > node.data, we should use recursive function, at this point, 'insert', thus keep running until new data(which is we just add) puts on the right position.
Another method, 'Delete' was almost similar to 'insert' method, except two more cases we should consider.
Since I am quite familiar to binary tree because of preparation of term test 2, week 9's lecture was quite simple, and understandable.
The one thing I am worrying about is lab because it is hard to review and study lab every week without tutorials. I need TA's help during tutorials about lab since the solutions of labs are not posted until few days before term tests.
Piazza does not help that much as TA's. I want quick response, quick help from TAs about lab.
I hope strike will be over on next week!
No comments:
Post a Comment