First, the definition
The dictionary tree is also called the word search tree ,trie tree , is a kind of tree structure, is a kind of hash tree variant. Typical applications are used for statistics, sorting, and saving a large number of strings (but not limited to strings), so it is often used by search engine systems for text frequency statistics. Its advantages are: the use of the common prefix of the string to save storage space, minimize unnecessary string comparisons, query efficiency is higher than the hash table.
The dictionary tree is very similar to the dictionary, when you want to look up a word is not in the dictionary tree, first look at the first letter of the word is not in the first layer of the dictionary, if not, the dictionary tree does not have the word, if in the child node in the letter is not a second letter, there is no description of the word, Some words continue to search in the same way. The dictionary tree can be used not only to store letters, but also to store numbers and other data.
Second, Java code implementation
//Java implementation of the dictionary tree Public classTrie {PrivateTrienode Root; PublicTrie () {root=NewTrienode (); Root.wordend=false; } Public voidInsert (String Word) {trienode node=Root; for(inti = 0; I < word.length (); i++) {Character C=NewCharacter (Word.charat (i)); if(!Node.childdren.containsKey (c)) {Node.childdren.put (c,NewTrienode ()); } node=Node.childdren.get (c); } node.wordend=true; } Public BooleanSearch (String word) {trienode node=Root; BooleanFound =true; for(inti = 0; I < word.length (); i++) {Character C=NewCharacter (Word.charat (i)); if(!Node.childdren.containsKey (c)) { return false; } node=Node.childdren.get (c); } returnFound &&Node.wordend; } Public BooleanstartsWith (String prefix) {trienode node=Root; BooleanFound =true; for(inti = 0; I < prefix.length (); i++) {Character C=NewCharacter (Prefix.charat (i)); if(!Node.childdren.containsKey (c)) { return false; } node=Node.childdren.get (c); } returnfound; } } Public classTrienode {Map<character, trienode>Childdren; BooleanWordend; PublicTrienode () {Childdren=NewHashmap<character, trienode>(); Wordend=false; } }
Java implementation of the Dictionary tree (Trie)