Unit 2

Search Algorithms II

[19.1] What properties must a tree have for it to be a BST?

[19.2] If we know that a tree T is a BST, do we know anything special about subtrees T[“left”] and T[“right”]?

[19.3] Label each of the following as a BST, binary tree, or regular tree. Image Description

[19.4] Assume that we have a tree of n nodes.

  1. What does it mean for out tree to be balanced?
  2. If it is balanced, what is the big-O runtime of binary searching the tree?
  3. If it is balanced, what is the big-O runtime of linear searching the tree?
  4. If it is unbalanced, what is the big-O runtime of binary searching the tree?
  5. If it is unbalanced, what is the big-O runtime of linear searching the tree?

[19.5] In lecture, we discussed how hashed search is somewhat analogous to finding your post boxes in the UC. Please list another example of how we encounter hashed searches in our lives.

[19.6] Hash functions map values to _____? What rules must a hash function follow?

[19.7] What is a collision? Describe in words what are some characteristics of a bad hash function? How might this affect the performance of our hashed search?

[19.8] Given a value x, a hash function f, and a hash table T, describe the process of how you would put value x into hash table T. How would you look up the value x later on?

[19.9] What types of data can we not place into a hashtable? Why?

[19.10] What does hashing have to do with dictionaries?

[19.11] Consider the following BST: Image Description

List the numbers you would visit if you ran a search algorithm looking for the following values:

  1. 18
  2. 32
  3. 40
  4. 9

[19.12] Using the function stringHash, place the following values in the given hash table: “onion”, “noble”, “wolf”, “flowers”, “ash”. Feel free to use the ASCII Table for this question.

            
def stringHash(x):
   if len(x)<=4:
       return ord(x[len(x)//2]) + len(x)
   else:
       return ord(x[-1]) - len(x)*2

            
        

[19.13] Is the above a good hash function? Why or why not?

[19.14] Write a function getLargest(T) which returns the largest element of the given BST.

[19.15] Which of these values can we hash? What makes something hashable?

“Hello”, ‘H’, [“hello”, 2], 3, True

[19.16] Write the code for how to do linear search on a Tree. Assume your function takes a tree and a target as parameters.

[19.17] Are the given trees BSTs? Why or why not? Image Description

[19.18] Write the code for how to do binary search on a BST. Assume your function takes a tree and a target as parameters.

[19.19] Why might a binary search tree be preferred over a sorted list?

[19.20] What is the runtime of the following operations? Why?

  1. item in lst where lst is a list of elements
  2. item in dict where dict is a dict of key-value pairs