Ouney
Ouney

Reputation: 1194

Trie - Implementation in java

I know there is plenty of material available regarding it but i had quite specific questions. I have a file containing postal codes and i have to create trie data structure using those codes. I have written my implementation which is -

public class Trie{

TrieNode root = null;

public void addWord(String zipCodeStr){
    if(root==null){
        root = new TrieNode();
    }
    TrieNode current = root;
    for(char c : zipCodeStr.toCharArray()){
        if(current.childern[Character.getNumericValue(c)]==null){
            current.childern[Character.getNumericValue(c)] = new TrieNode();
        }
        current = current.childern[Character.getNumericValue(c)];
    }
    current.isWord = true;
}

public boolean exists(String zipCodeStr){
    boolean result = true;
    TrieNode current = root;
    for(char c : zipCodeStr.toCharArray()){
        if(current.childern[Character.getNumericValue(c)]==null){
            result = false;
            break;
        }
        current = current.childern[Character.getNumericValue(c)];
    }
    if(result && current.isWord){
        result = true;
    }else{
        result = false;
    }
    return result;
}

private static class TrieNode{

    TrieNode[] childern = new TrieNode[10];
    boolean isWord = false;

    public TrieNode() {
    }

}
}

Here, i am not storing any value as position gives that information.

Questions - i) Can it be further improvised? ii) Raw text file size containing 27000+ codes is around 190kb and i checked the size of trie object using a profiler it came out to be much more. Profiler output Are these two size related? Should trie size be less than raw text file size?

Thanks, Ouney

Upvotes: 1

Views: 362

Answers (1)

Alex Salauyou
Alex Salauyou

Reputation: 14338

Supposing that ~9/10 nodes are leafs (don't contain children), you can significantly decrease space that whole structure occupies by lazy initialization of children array:

private static class TrieNode {
    TrieNode[] children = null;  
    boolean isWord = false;
}

Now you need to create a new array only if it is actually needed:

public void addWord(String zipCodeStr) {
   if (root == null){
        root = new TrieNode();
   }
   TrieNode current = root;
   for (char c : zipCodeStr.toCharArray()) {
       if (current.children == null) {
           current.children = new TrieNode[10];
       }
       if (current.children[Character.getNumericValue(c)] == null) {
           current.children[Character.getNumericValue(c)] = new TrieNode();
       }
       current = current.children[Character.getNumericValue(c)];
   }
   current.isWord = true;
}

Upvotes: 3

Related Questions