Search code examples
javatrie

Traversing a Trie


I am trying to traverse a trie in preorder in Java. I need to do some operations if i have found a leaf. I call the Method with the root of the tree and a empty String "" that i can go into the recursion. I have stored a String in every Node and mark words as leaf. For example "the" would be find through the following nodes: ""-->"t"-->"th"-->"the". Thats what I have so far:

void traverse(TrieNode current, String prefix){
  for (TrieNode temp : current.getChildren()) {
                if (temp == null) continue;
                String s = temp.getKey();
                traverse(temp, s);
                if (temp.getIsLeaf()) {
                   //do operations
                }
   }
}

Can someone help me to find a working Solution?


Solution

  • A preorder means you first visit the root, then the children. I didn't understand your use of String prefix (it's available thru current.getKey() anyway)

    void traverse(TrieNode current, String prefix){
      // do what you need with the key...
      String currentValue = current.getKey();
      // do what you need if leaf
      if (current.getIsLeaf()) {
        // do operations
      }
      for (TrieNode temp : current.getChildren()) {
          traverse(temp);
       }
    }