Search code examples
javadictionarytreetrie

Trying to print all words in a trie in java


I'm using a trie structure called a dictionary tree which I want to print all words from. When I insert a word when I reach the last letter in the word I store the completed word in Dictionary Tree.

private Map<Character, DictionaryTree> children = new LinkedHashMap<>();

private String completeWord;

void insertionHelper(String currentPortion, String fullWord){
    if(currentPortion.length() == 1){
        if(children.containsKey(currentPortion.charAt(0))){
           // do nothing

        }else{
            this.children.put(currentPortion.charAt(0), new DictionaryTree());
        }
        this.completeWord = fullWord;
    }else{
        if(children.containsKey(currentPortion.charAt(0))){
            children.get(currentPortion.charAt(0)).insertionHelper(currentPortion.substring(1), fullWord);
        }else{
            DictionaryTree a = new DictionaryTree();
            a.insertionHelper(currentPortion.substring(1), fullWord);
            children.put(currentPortion.charAt(0), a);
        }
    }

}

After this when Looking for all words I traverse every node and try to add the words to a static array List, however, for some reason many of the words are duplicated and others are missing.

String allWordHelper(){

    String holder = " ";
    for (Map.Entry<Character, DictionaryTree> child : children.entrySet()) {
        if(completeWord != null){
            //holder += completeWord + child.getValue().allWordHelper();
            Word_Holder.allWords.add(completeWord);

        }else{
            holder += child.getValue().allWordHelper();
        }

    }

    return holder;
}

I can't figure out why.


Solution

  • I have no idea what a DictionaryTree is and what your indata looks like but if you do

    children.put(currentPortion.charAt(0), a);
    

    doesn't that mean that whenever you get a words that starts with the same character as a previous word then the old word might be replaced by the new one?

    It's quite impossible to fully understand your code with an unknown data type and all the recursive calls.