Trie tree, also known as the Dictionary tree and prefix tree, is a multi-fork tree for fast retrieval. The tried tree can take advantage of the common prefix of a string to conserve storage space.
However, if the system has a large number of strings without a public prefix, the corresponding trie tree will consume memory very much. (For the Trie tree on the wiki, Https://en.wikipedia.org/wiki/Trie)
- Child nodes are represented by HashMap
- Isword tags from the root node to whether the node represents a word, or a prefix for another word.
Implement a trie with insert , search , and startsWith methods.
classTrienode {//Initialize your data structure here. BooleanIsword; PublicHashmap<character,trienode>nexts; PublicTrienode () {nexts=NewHashmap<character,trienode>(); } } Public classTrie {PrivateTrienode Root; PublicTrie () {root=NewTrienode (); } //inserts a word into the trie. Public voidInsert (String word) {intStart=0; intEnd=word.length (); Trienode P=Root; while(start<end) {trienode node=P.nexts.get (Word.charat (start)); if(node!=NULL) {p=node; Start++; }Else Break; } while(start<end) {Trienode Trie=NewTrienode (); P.nexts.put (Word.charat (start), trie); P=trie; Start++; } P.isword=true; } //Returns If the word is in the trie. Public BooleanSearch (String word) {Trienode P=Root; for(intI=0;i<word.length (); i++) {Trienode child=P.nexts.get (Word.charat (i)); if(child==NULL){ return false; } P=Child ; } returnP.isword; } //Returns If there is any word in the trie//That's starts with the given prefix. Public BooleanstartsWith (String prefix) {trienode p=Root; for(intI=0;i<prefix.length (); i++) {Trienode child=P.nexts.get (Prefix.charat (i)); if(child==NULL)return false; P=Child ; } return true; }}//Your Trie object would be instantiated and called as such://Trie Trie = new Trie ();//Trie.insert ("somestring");//trie.search ("key");
[Leedcode 208] Implement Trie (Prefix Tree)