Lecture 19 - Problems

  1. In a BST or AVL Tree, the order of insertion determines the tree’s structure. Is the same true for Tries?

Some basic skeleton code for the following problems can be found here, with some helpful details filled in and a few (very) cursory test cases. Feel free to develop your code on a computer and see if it works!

  1. A basic and non-generic TrieNode class for a Set of Strings is defined as follows:

    class TrieNode {
      HashMap<String, TrieNode> children;
      boolean terminates;
    }

    Implement the insert operation, which is an instance method of the TrieNode class:

    /** Insert word into the Set represented by this trie.
     * Returns whether the Set changed. Precondition: word is not null. */
    public boolean insert(String word) {
    
      // your code here
    
    }
  2. Write code for the following method, which is a static method that takes a TrieNode as an argument:

    /** Return the number of words in the trie rooted at n that begin with
     * the given prefix. If the prefix itself is a word, that is counted.
     * Precondition: prefix is not null. */
    public static int prefixFrequency(TrieNode n, String prefix) {
    
      // your code here
    
    }
  3. What’s the worst-case runtime of the method from Problem 2?

  4. Suppose we need to calculate prefix frequencies more efficiently than that.

    1. Modify the TrieNode class above to support a prefixFrequency that operates in constant time (you’ll need to use some extra storage in exchange for a faster runtime).

    2. Write code for prefixFrequency (same spec as above) that operates on your modified TrieNode and runs in O(1) time.

    3. Modify your code for insert (same spec as above) to work with the modified TrieNode.