コード例 #1
0
 private void insertIntoTree(TrieNode2 _root, String _word) { // 插入一个单词	
   if (null == _root || null == _word || "".equals(_word)) return;
   char[] cs = _word.toCharArray(); // 将字符串转化为字符数组
   for (int i = 0; i < cs.length; i++) {
     int index; // 对应的索引值
     if (cs[i] >= 'A' && cs[i] <= 'Z') {
       index = cs[i] - 'A';
     } else if (cs[i] >= 'a' && cs[i] <= 'z') index = cs[i] - 'a';
     else return;
     // !!!
     TrieNode2 child_node = _root._children[index];
     if (null == child_node) { // 如果没找到
       TrieNode2 new_node = new TrieNode2(cs[i]); // 创建新节点
       // 如果遍历到该单词最后一个字符
       // !!!
       if (i == cs.length - 1) {
         new_node.setIsWord(true); // 把该单词存在树中
       }
       _root._children[index] = new_node; // 连接该节点
       _root = new_node;
     } else {
       _root = child_node; // 更新树根
     }
   }
 }
コード例 #2
0
 private void printTree(TrieNode2 _root, List<Character> list) {
   if (_root == null) {
     return;
   }
   if (_root.isWord()) { // 如果根节点到此节点构成一个单词则输出
     for (char c : list) {
       System.out.print(c);
     }
     System.out.println();
   }
   for (TrieNode2 node : _root._children) { // 遍历树根孩子节点
     if (node != null) { // 回溯法遍历该树
       list.add(node.getValue());
       // _word[index++] = node.getValue();
       printTree(node, list);
       // _word[index] = ' ';
       list.remove(list.size() - 1);
     }
   }
 }
コード例 #3
0
  private boolean searchWord(TrieNode2 _root, String _word) {
    if (null == _root || null == _word || "".equals(_word)) return false;
    char[] cs = _word.toCharArray(); // 将字符串转化为字符数组
    for (int i = 0; i < cs.length; i++) {
      int index;
      if (cs[i] >= 'A' && cs[i] <= 'Z') {
        index = cs[i] - 'A';
      } else if (cs[i] >= 'a' && cs[i] <= 'z') index = cs[i] - 'a';
      else return false;

      TrieNode2 child_node = _root._children[index];
      if (child_node == null) {
        return false;
      } else {
        _root = child_node;
      }
    }

    return _root.isWord();
  }