public class trie{ private Node root; Public Trie () { root = new Node ('); } public void Insert (String word) { if (search (word) = = true) return; Node current = root; for (int i = 0; i < word.length (), i++) { Node child = Current.subnode (Word.charat (i)); if (child! = null) {Current = child; } else { current.childList.add (new Node (Word.charat (i))); Current = Current.subnode (Word.charat (i)); } current.count++; } Current.isend = true; }
/** * How to tell if a word exists ? * The letter of the judged word is compared to the letter of the child node under the root node until it matches the last letter of the two, and the last node's isend is marked true */public boolean search (String word) {Node cur Rent = root; for (int i = 0; i < word.length (); i++) {if (Current.subnode (Word.charat (i) = = null) retur n false; else current = Current.subnode (Word.charat (i)); } if (current.isend = = true) return true; else return false; The public void Deleteword (String word) {if (search (word) = = false) return; Node current = Root;for (char c:word.tochararray ()) {Node child = Current.subnode (c); if (Child.count = = 1) {Current.child List.remove (child); return;} else {child.count--;current = child;}} Current.isend = false;}
public static void Main (string[] args) {Trie Trie = new Trie (),//trie.insert ("Ball"), Trie.insert ("balls"); Trie.deleteword ("Balls"); Trie.insert ("sense");//Testing DeletionSystem.out.println (Trie.search ("Balls")); System.out.println (Trie.search ("ba")); Trie.deleteword ("Balls"); System.out.println (Trie.search ("Balls")); System.out.println (Trie.search ("ball"));}}
Class Node { char content;//node contains a Boolean isend;//whether the node line is a word int count; Statistics the character of the node is shared by several words linkedlist<node> childlist;//The collection of child nodes//Initialize public node (char c) { childlist = New Linkedlist<node> (); Isend = false; Content = C; Count = 0; } Finds whether the child node has a child node with the content X, or returns the child node, otherwise returns null public node subnode (char c) { if (childlist! = null) {for (node Eachchild:childlist) { if (eachchild.content = = c) { return eachchild; }} } return null;} }
Trie Tree (dictionary tree) Java implementation