0

I'm trying to write a simple search engine which uses trie(a node contains just one character) data structure to find the words. And when it gets the "compress" command from user, the trie should turn into a form of a patricia trie.(a node contains strings that are common with their children)

i have done the concatenating the strings part, but the problem is children concatenated with their parent are still there.(They should have been deleted.) And i thought, by writing a "clear" method, I could deal with it.

Here is my solution, but it is not working:

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);
        }
    }

}

Here is the main, and the output:

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();
}

Output:

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 

How can I deal with this problem? Any help will be appreciated. Thanks a lot!

sha1
  • 153
  • 7

1 Answers1

0

The problem is how you try to clear the children.

This part:

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;
    }
    ....
}

Does not remove the child, it sets the reference to the child in the to null, but it leaves the children in c intact. You must tell v to remove the child.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53