我正在尝试编写一个简单的搜索引擎,它使用trie(一个节点只包含一个字符)数据结构来查找单词。当它从用户那里得到"compress“命令时,trie应该变成一种a patricia trie形式(一个节点包含其子节点共有的字符串)。
我已经完成了字符串部分的连接,但问题是,与其父节点连接在一起的子节点仍然存在(它们应该已经被删除)。我想,通过写一个“清晰”的方法,我可以处理它。
以下是我的解决方案,但它不起作用:
public void toPatriciaTrie() {
toPatriciaTrie(root);
clearTheTrie(root); // the method call is here.
}
public void clearTheTrie(Node<String> v) {
for (Node<String> w : v.getChildren()) {
// finds out if the parent contains the children
// if yes, deletes the children.
if (v.getElement().indexOf(w.getElement()) != -1) {
w = null;
}
else if (w != null) {
clearTheTrie(w);
}
}
}下面是main和输出:
Main:
public static void main(String[] args) {
Trie trie = new Trie();
System.out.println("false " + trie.contains("stack"));
// here the second one is the name of the file containing the word
// and the other one is its index in the file.
trie.addToTrie("stack", "asd.txt", 3);
trie.addToTrie("star", "asd.txt", 5);
trie.addToTrie("jaws", "asdf.txt", 7);
trie.addToTrie("java", "asdadsad.txt", 9);
System.out.println("true " + trie.contains("stack"));
System.out.println("true " + trie.contains("star"));
System.out.println("true " + trie.contains("jaws"));
System.out.println("true " + trie.contains("java"));
trie.print();
trie.toPatriciaTrie();
System.out.println();
trie.print();
}输出:
false false
true true
true true
true true
true true
j a v a w s s t a r c k
ja a va a ws s sta ta a r ck k 我该如何处理这个问题?任何帮助都将不胜感激。非常感谢!
发布于 2013-06-30 19:08:46
问题是您如何尝试清空孩子。
这部分:
for (Node<String> w : v.getChildren()) {
// finds out if the parent contains the children
// if yes, deletes the children.
if (v.getElement().indexOf(w.getElement()) != -1) {
w = null;
}
....
}不移除子对象,它会将中对子对象的引用设置为null,但会使c中的子对象保持不变。您必须告诉v删除该子对象。
https://stackoverflow.com/questions/17388332
复制相似问题