Class Trie{private int size=26;private trienode root;//The root of the Dictionary tree Trie () {//Initialize the dictionary tree root=new Trienode ();} Private class trienode{//Dictionary tree node private int num;//How many words pass through this node, that is, the number of times the node character appears private trienode[] son;//all the son node private Boolean isend;//is not the last node private char val;//node value Trienode () {num=1;son=new trienode[size];isend=false;}} Create a dictionary tree public void Insert (String str) {//Insert a word in the dictionary tree if (str==null| | Str.length () ==0) {return;} Trienode node=root;char[] Letters=str.tochararray (); for (int i=0,len=str.length (); i < len;i++) {int pos=letters[i]- ' A '; if (node.son[pos]==null) {node.son[pos]=new trienode (); node.son[pos].val=letters[i];} else{node.son[pos].num++;} Node=node.son[pos];} Node.isend=true;} Computes the number of word prefixes public int countprefix (String prefix) {if (Prefix==null | | prefix.length () ==0) {return-1;} Trienode node=root;char[] Letters=prefix.tochararray (); for (int i=0,len=prefix.length (); i<len;i++) {int pos= letters[i]-' a '; if (node.son[pos]==null) {return 0;} Else{node=node.son[pos];}} return node.num;} Find an exact word in the dictionary tree. Public booleanHas (String str) {if (Str==null | | str.length () ==0) {return false;} Trienode node=root;char[] Letters = Str.tochararray (); for (int i=0,len=str.length (); i<len;i++) {int pos= letters[i]- ' A '; if (node.son[pos]!=null) {Node=node.son[pos];} Else{return false;}} return node.isend;} The pre-order traversal dictionary tree. public void Pretraverse (Trienode node) {if (node!=null) {System.out.print (node.val+ "-"); for (Trienode Child: Node.son) {pretraverse (child);}}} Public Trienode Getroot () {return this.root;} public static void Main (string[] args) {Trie tree=new Trie (); String[] strs={"Banana", "Band", "Bee", "Absolute", "ACM",}; string[]prefix={"ba", "B", "Band", "ABC",};for (String str:strs) {tree.insert (str);} System.out.println (Tree.has ("abc")); Tree.pretraverse (Tree.getroot ()); System.out.println (); for (String pre:prefix) {int num=tree.countprefix (pre); System.out.println (pre+ "" +num);}}Specifically read the encyclopedia: http://baike.baidu.com/link?url=bImDvvYau9FWbZKr64ExkxvXOZb_Df-b7O2YCPHyqH_ Orknkooi6jt4o-3a9xqorwbugantibeq0pfjx-gvu8_
Dictionary tree Templates (Java)