Example #1
0
 /* Find a child node of this node that has the char argument as its
  * data. Return null if no such child node is present in the trie.
  */
 TrieNode getChild(char c) {
   for (TrieNode t : children) {
     if (t.getChar() == c) {
       return t;
     }
   }
   return null;
 }
Example #2
0
  /* Add the String passed in as argument to the trie, starting at a
   * child node of this node. If any prefix of this String is already
   * present in the trie starting from a child node of this node, only
   * add the remaining part of the String to the trie, at the
   * appropriate position in the trie.
   */
  public void addWord(String word) {
    if (word == null || word.isEmpty()) {
      return;
    }

    TrieNode child;
    char firstChar = word.charAt(0);

    TrieNode t = getChild(firstChar);

    if (t == null) {
      child = new TrieNode(firstChar);
      children.add(child);
    } else {
      child = t;
    }

    if (word.length() > 1) {
      child.addWord(word.substring(1));
    } else {
      child.setTerminates(true);
    }
  }