Tries
Tries
A trie is a multiway search tree based on the idea that a key value can often be written as a string of digits or characters.. It's also known as a radix tree or a digital search tree. It will be particularly useful for the implementation of your Boggle game, so we are going to implement it in Tuesday's lab.A trie can be used to implement either a set. Set is a java interface with the following fundamental operations (among others):
- boolean add(Object object); // add the object to the set, if it is not already in the set. Return value is true if and only if the set is modified as a result of this operation.
- boolean contains(Object object); // returns true if and only if the set contains the given object.
A trie can be used to hold a set of character strings, by considering the characters to be the digits of a number whose radix is the number of characters in the alphabet. For example, we can consider strings of the letters "a" through "z" to be numbers written with radix 26.
Consider the following Trie. It assumes an alphabet of the letters { a, b, c, d } and hold the strings "b", "abc" "abab", dad", "da", and dab. All slots which do not contain a red link contain the value "null".
Searching the Trie
To search for a given string with characters c1, c2, ..., cn:- Start at the root (level 0)
- At level i, follow the link to the (ci+1)-st child of the node.
- If you find a null pointer before arriving at level n, then the string is not found in the trie.
- If you arrive at a node at level n, then the isWord flag in that node
indicates whether or not the word is in the table.
Inserting a word in a Trie
To insert a word in a trie:- Follow the same path (starting at the root) that you would follow in searching for the word.
- If you hit a null pointer along the way, create a new node, set its isWord flag to "false", and continue.
- When you reach level n, set the "isWord" flag to true.
Analysis:
What is the order of the running time of the search and insert operations? How does this compare with a (balanced) binary search tree?Are there any disadvantages to the use of a trie as a Set or Map?
How much space is used by a trie? How does this compare with a (balanced) binary search tree?
How would you write a program to traverse a trie; that is, visit each word stored in the trie, in lexicographic order?