首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Patricia Trie的Trie

Patricia Trie的Trie
EN

Stack Overflow用户
提问于 2013-06-30 15:55:05
回答 1查看 777关注 0票数 0

我正在尝试编写一个简单的搜索引擎,它使用trie(一个节点只包含一个字符)数据结构来查找单词。当它从用户那里得到"compress“命令时,trie应该变成一种a patricia trie形式(一个节点包含其子节点共有的字符串)。

我已经完成了字符串部分的连接,但问题是,与其父节点连接在一起的子节点仍然存在(它们应该已经被删除)。我想,通过写一个“清晰”的方法,我可以处理它。

以下是我的解决方案,但它不起作用:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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();
}

输出:

代码语言:javascript
复制
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 

我该如何处理这个问题?任何帮助都将不胜感激。非常感谢!

EN

回答 1

Stack Overflow用户

发布于 2013-06-30 19:08:46

问题是您如何尝试清空孩子。

这部分:

代码语言:javascript
复制
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删除该子对象。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17388332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档