More over, we have discuessed in BST again but more deeply such that insert and delete function(lab) which was similar to what we covered couple weeks ago.
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
The complete insert function as show above. The insert function basically just search the correct position and insert value into corresponding place. Function runs recursively that go through elements in tree and put value in right position.
Mingyi,
ReplyDeleteI agree that Minimax was definitely a difficult function to implement that required a great understanding of the recursive process. I also found that recursion on Binary Search Trees was one of the easier recursions to implement since all the cases are laid out for you. All you have to do is analyze whether the value in question is less, greater than the root, or within certain range and then decide accordingly through which subtree to recurse. Also, from our recent lectures on efficiency, a balanced BST is O(logn) for functions like insert, delete, or search which makes it a very useful data structure.