I want to print or retrieve all the words stored in Trie Data Structure. This is because I want to compute Edit distance between a misspelled word and a word in Dictionary.
Therefore I was thinking of retrieving each word from Trie and compute Edit distance.
But I am not able to retrieve. I want some code snippet for this.
This is how I have implemented the Trie using HashMap
in Java
Now please tell me how to write code for printing all words stored in Trie. Any help is very much appreciated
TrieNode.java
package triehash;
import java.io.Serializable;
import java.util.HashMap;
public class TrieNode implements Serializable {
HashMap<Character, HashMap> root;
public TrieNode() {
root = new HashMap<Character, HashMap>();
}
}
TrieDict.java
package triehash;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;;
import java.io.Serializable;
import java.util.HashMap;
import java.io.Serializable;
public class TrieDict {
public TrieNode createTree()
{
TrieNode t = new TrieNode();
return t;
}
public void add(String s, TrieNode root_node) {
HashMap<Character, HashMap> curr_node = root_node.root;
s = s.toLowerCase();
for (int i = 0, n = s.length(); i < n; i++) {
Character c = s.charAt(i);
if (curr_node.containsKey(c))
curr_node = curr_node.get(c);
else {
curr_node.put(c, new HashMap<Character, HashMap>());
curr_node = curr_node.get(c);
}
}
curr_node.put('\0', new HashMap<Character, HashMap>(0)); // term
}
public void serializeDict(TrieNode root_node)
{
try{
FileOutputStream fout = new FileOutputStream("/home/priya/NetBeansProjects/TrieHash/dict.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(root_node);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
public void addAll(String[] sa,TrieNode root_node) {
for (String s: sa)
add(s,root_node);
}
public static void main(String[] args)
{
TrieDict td = new TrieDict();
TrieNode tree = td.createTree();
String[] words = {"an", "ant", "all", "allot", "alloy", "aloe", "are", "ate", "be"};
for (int i = 0; i < words.length; i++)
td.add( words[i],tree);
td.serializeDict(tree); /* seriliaze dict*/
}
}