According to Wikipedia, regarding trie:
Lexicographic sorting of a key set can be performed using a simple trie-based algorithm as follows:
- Insert all the keys into the trie.
- Print all the keys in trie by traversing the pre-order, which leads to the conclusion, which is in lexicographically increasing order.
However, this is my testing with my standard trie implementation:
Trie trie = new Trie();
trie.add("doll");
trie.add("ball");
trie.add("bat");
trie.add("dork");
trie.add("dorm");
trie.add("send");
trie.add("sense");
trie.add("sent");
Printout of pre-order:
public List<String> allWords(){
List<String> words = new ArrayList<String>();
if(root == null){
return words;
}
StringBuilder prefix = new StringBuilder();
getAllWords(root.children,prefix,words);
return words;
}
private void getAllWords(List<TrieNode> children, StringBuilder prefix, List<String> words){
for(int i= 0; i<children.size(); i++){
TrieNode child = children.get(i);
if(!child.isWord_){
prefix.append(child.data_);
allWordsHelper(child.children, prefix, words);
}else{
prefix.append(child.data_);
words.add(prefix.toString());
}
prefix.deleteCharAt(prefix.length()-1);
}
}
And the output order: doll dork dorm ball bat send sense sent
" "? , , . - ?
, " ". ?